1

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

private T GenericMethod<T>(String value)
{  
    return (T)Enum.Parse(typeof(T), value , true);  
}
1
  • Neither C# nor Java have templates. edit: edited. Commented Jul 8, 2011 at 11:57

2 Answers 2

4

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);    
Sign up to request clarification or add additional context in comments.

Comments

1

First change your method signature to the following :

private <T> T TemplateMethod(String value)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.