2

Let's say I have a string with a value

'Language'

And I have an enum called Language

enum Language{
    English,
    Spanish,
    French
}

Is there a way to use the string 'Language' and return the values of the Enum Language. I'm basically wondering if there is a method to get an instance of the Enum Language by passing in a string. Kind of like

Class.forName()

but for enums.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Daniel Langer
  • 106
  • 1
  • 11

1 Answers1

6

An enum is a class, so with the fully qualified name (eg, "com.mydomain.myapp.Language") you can get the enum's class from Class.forName. From there, you can use reflection on the Class object: getEnumConstants gives you all the enum's values, and if you want names instead you can just use .name on the Enum objects.

amalloy
  • 89,153
  • 8
  • 140
  • 205
  • what is com.mydomin.myapp? Plus my enum is in a package so how do I include that in the name – Daniel Langer Aug 02 '12 at 19:28
  • Fully qualified name of class [as in docs](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#forName(java.lang.String)). – Grzegorz Rożniecki Aug 02 '12 at 19:30
  • I think it is the correct answer and just want to add another link with the tutorial from Oracle showing just how to use reflection to get the values : http://docs.oracle.com/javase/tutorial/reflect/special/enumMembers.html –  Aug 02 '12 at 19:30
  • I've never really understood fully qualified class name. If my app is called Notebook and the enum is called Language in a package called Notes, what would the fully qualified name be? – Daniel Langer Aug 02 '12 at 19:32
  • @Daniel: you have tons of Java tutorials explaining that, eg http://docs.oracle.com/javase/tutorial/java/package/packages.html – leonbloy Aug 02 '12 at 19:37