Get interface constant name using its value
Have converted this to a generic method, for improved reusability (eg. for switch
& default
):
/**
* @param cls The *.class which to traverse
* @param value The constant value to look for
*/
@Nullable
private String getConstantName(Class<?> cls, int value) {
for (Field f : cls.getDeclaredFields()) {
int mod = f.getModifiers();
if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && Modifier.isFinal(mod)) {
try {
// Log.d(LOG_TAG, String.format("%s = %d%n", f.getName(), (int) f.get(null)));
if((int) f.get(null) == value) {return f.getName();}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return null;
}
I can think of two better solutions to this than using reflection.
Any decent IDE will auto-fill in switch statements for you. I use IntelliJ and it does this (you just press ctrl-enter). I'm sure Eclipse/Netbeans have something similar; and
Enums make a far better choice for constants than public static primitives. The added advantage is they will relieve you of this problem.
But to find out what you want via reflection, assuming:
interface Foo {
public static final int CONST_1 = 1;
public static final int CONST_2 = 3;
public static final int CONST_3 = 5;
}
Run:
public static void main(String args[]) {
Class<Foo> c = Foo.class;
for (Field f : c.getDeclaredFields()) {
int mod = f.getModifiers();
if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && Modifier.isFinal(mod)) {
try {
System.out.printf("%s = %d%n", f.getName(), f.get(null));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
Output:
CONST_1 = 1
CONST_2 = 3
CONST_3 = 5