I have an enum declared like this:
public enum Mode{
RUNNING("SytemRunning"),
STOPPED("SystemStopped"),
IDLE("tmpIdle");
public static String key;
private Mode(String key){
this.key = key;
}
}
Now, I want to get out the keys(SystemRunning, SystemStopped, tmpIdle) for this enum by reflection:
Class<?> c = Class.forName("Mode");
Object[] objects = c.getEnumConstants();
// now this is not what I want, but almost
for(Object obj : objects){
System.out.println("value : " + obj);
}
the output is: RUNNING STOPPED IDLE
However, I'd like to have the Strings SystemRunning, tmpIdle etc..
Thank you very much in advance.
Add a method toString() that returns your key, then it will work. Your 'key' property shouldn't be static.
If you know that all your enums have a key property, you can ask for it directly by reflection too.
Get 'key' with reflection:
There is no point using reflection for this:
Firstly, you need to make your
key
a non-static variable.Then you need to add a getter method in your enum which will return the
key
and then change your
for
loop to something like this.