1

I need to create a generic function that will parse enums from strings, but i'm not sure about the syntax to use.

This doesn't work, but it illustrate what i want to do :

public <E extends Enum<E>> getEnum( some params, <E extends Enum<E>> defaultVal )
{
    // Some stuff

    return E.valueOf( enumAsString );
}

What is wrong in my syntax please ? Thank you :)

EDIT : Also how do i use this ? In C++ i would do SomeEnum e = getEnum<SomeEnum>( ... );

EDIT :

Let

enum EnumA
{
    A_A, A_B, A_C
};

enum EnumB
{
    B_A, B_B, B_C
};

I would like to do :

String enumAsStr = "A_B";
EnumA ea = getEnum< EnumA >( enumAsStr, "A_A" );

enumAsStr = "B_C";
EnumB eb = getEnum< EnumB >( enumAsStr, "B_A" );
7
  • Am I getting this right: You want to find an Enum by one of its elements given as String? Commented Aug 25, 2014 at 14:02
  • Yes the enum as it appears in the source code is stored in the given string, and i also pass a default value in case the parsing fails. Commented Aug 25, 2014 at 14:02
  • I guess what you are looking for is called "reflection". Commented Aug 25, 2014 at 14:04
  • Yes but that's very vague. I know how to get the value of an enum from it's name, i just don't know the Java syntax to use for a function returning a generic type that can only be an enum. Commented Aug 25, 2014 at 14:05
  • Ah, ok. I see. So I guess Edwin has your answer. Commented Aug 25, 2014 at 14:06

1 Answer 1

5

You could do something like

public <E extends Enum<E>> E getEnum( String text, Class<E> klass){
   return Enum.valueOf(klass, text );
}

So, for instance if there is an enum Letter

public enum Letter { A, B, C}

You could use it like this:

Letter someLetter = getEnum("A", Letter.class);
System.out.println(someLetter); //A
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer. That looks to be what i'm looking for, but in my example the last parameter was used for a default enum to return in case the parsing fails. In my example "E" reprensts my enum type right ? Can't i do E.valueOf(someString) ?
Couldn't i do instead : public <E extends Enum<E>> E getEnum( String text ) { Class< E > klass; return Enum.valueOf( klass.class, text ); }
You can't. Enum.valueOf need a class of some enumerate to do its works. And beside, you don't initialize it, and if you could, you would have problems with type erasure.

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.