Reputation: 103
I have an enum. And a string contains the name of the enum. I want to access the enum using the string. Something like this. But this does not work :(
public enum Level { HIGH, MEDIUM, LOW }
def x = "Level"
println "$x".values();
Upvotes: 0
Views: 68
Reputation: 2376
You have to do it like this:
public enum Level { HIGH, MEDIUM, LOW }
def x = this.class.classLoader.loadClass('Level', true)
println x.values()
Here's an alternative way:
public enum Level { HIGH, MEDIUM, LOW }
def x = "Level"
println Eval.me("${x}").values()
Upvotes: 0
Reputation: 1065
You can do it using Class.forName
method. For example
public enum Level {
HIGH,
MEDIUM,
LOW
}
def clazz = Class.forName("Level")
println clazz.values()
Remember you should use FULLY QUALIFIED CLASSNAME. For more details http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)
Upvotes: 1