I am using an imported class with has constant field values set using:
public static final int BLUE = 1;
public static final int GREEN = 2;
etc.
Is there any way of getting a string representation of the constant field value from the int value?
i.e. given the value 2 I want to get a string of GREEN.
P.S. This isn't my class so I can't use ENUMs
If you can change the class which contains these constants, it would be better to make it an enum with a value()
method.
Otherwise, I would suggest building a Map<Integer, String>
once using reflection, and then just doing map lookups:
Map<Integer, String> valueToStringMap = new HashMap<>();
for (Field field : Foo.class.getFields()) {
int modifiers = field.getModifiers();
if (field.getType() == Integer.class && Modifier.isPublic(modifiers)
&& Modifier.isStatic(modifiers)) {
valueToStringMap.put((Integer) field.get(null), field.getName());
}
}
See more on this question at Stackoverflow