Caner
Caner

Reputation: 59238

Convert C# generic into Java generic

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

private T GenericMethod<T>(String value)
{  
    return (T)Enum.Parse(typeof(T), value , true);  
}

Upvotes: 1

Views: 129

Answers (2)

Jord&#227;o
Jord&#227;o

Reputation: 56497

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);    

Upvotes: 4

dominicbri7
dominicbri7

Reputation: 2599

First change your method signature to the following :

private <T> T TemplateMethod(String value)

Upvotes: 1

Related Questions