开发者

Convert C# generic into Java generic

开发者 https://www.devze.com 2023-03-18 18:28 出处:网络
How can I convert the following C# code to Java? private T GenericMethod&开发者_StackOverflowlt;T>(String value)

How can I convert the following C# code to Java?

private T GenericMethod&开发者_StackOverflowlt;T>(String value)
{  
    return (T)Enum.Parse(typeof(T), value , true);  
}


Wherever you call your method:

// C#
MyEnum value = TemplateMethod<MyEnum>("AnEnumValue");

In Java you can do it like this:

// Java
MyEnum value = MyEnum.valueOf("AN_ENUM_VALUE");

If you're worried about case, and if you follow Java conventions of using upper case enum values, then you can just do this:

MyEnum value = MyEnum.valueOf(anEnumValue.toUpperCase());

To encapsulate it in a method:

static <E extends Enum<E>> E parse(Class<E> enumType, String value) {
  return (E)Enum.valueOf(enumType, value.toUpperCase()); 
}

Call it like this:

MyEnum value = parse(MyEnum.class, anEnumValue);    


First change your method signature to the following :

private <T> T TemplateMethod(String value)
0

精彩评论

暂无评论...
验证码 换一张
取 消