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)
精彩评论