I've read a lot about how obtain the corresponding name of an enum
from its value using java, but no example seems to work for me! What is wrong?
public class Extensions {
public enum RelationActiveEnum
{
Invited(0),
Active(1),
Suspended(2);
private final int value;
private RelationActiveEnum(final int value) {
this.value = value;
}
}
}
and in another class I use:
int dbValue = supp.ACTIVE;
Extensions.RelationActiveEnum enumValue(dbValue);
String stringName = enumValue.toString(); //Visible
// OR
int dbValuee = supp.ACTIVE;
String stringValue = Enum.GetName(typeof(RelationActiveEnum), dbValue);
I should work, right? but it doesn't!!!! it tells me that dbValue cannote be cast to RelationActiveEnum...
Since your 'value' also happens to match with ordinals you could just do:
And getting a enum from the value:
I guess an static method would be a good place to put this:
Obviously this all falls apart if your 'value' isn't the same value as the enum ordinal.
If you want something more efficient in runtime condition, you can have a map that contains every possible choice of the enum by their value. But it'll be juste slower at initialisation of the JVM.
This is my take on it:
And I have used it with System Preferences in Android like so:
where
pref
andeditor
areSharedPreferences
and aSharedPreferences.Editor
You could create a lookup method. Not the most efficient (depending on the enum's size) but it works.
And call it like this:
What you can do is
or
or
By if you want to lookup by a field of an enum you need to construct a collection such as a List, an array or a Map.
allows you to write
In my case value was not an integer but a String. getNameByCode method can be added to the enum to get name of a String value-