|
From: Kenneth B. R. <kbr...@al...> - 2002-06-14 16:00:35
|
> public static int getIntForConstant(String constant) {
Simpler and more efficient solution: use Class.getField.
public static int getIntForConstant(String constant) throws RuntimeException {
try {
Class c = GLEnum.class;
java.lang.reflect.Field f = c.getField(constant);
return f.getInt(c);
} catch (NoSuchFieldException e) {
throw new RuntimeException("Field " + constant + " not found");
}
}
NoSuchFieldException is a checked exception and its conversion into a
RuntimeException makes it easier to write code around it without allowing
silent failures like returning -1 would.
|