01: package abbot.util;
02:
03: import java.lang.reflect.*;
04:
05: import abbot.Log;
06:
07: /** Utility for performing some common reflection tasks. */
08:
09: public class Reflector {
10:
11: private Reflector() {
12: }
13:
14: /** Convert the value back into a field name. */
15: // NOTE: since this is an expensive lookup, maybe it should be deferred
16: // until just before needed?
17: public static String getFieldName(Class cls, int value,
18: String prefix) {
19: try {
20: Field[] fields = cls.getFields();
21: for (int i = 0; i < fields.length; i++) {
22: // Perform fastest tests first...
23: if ((fields[i].getModifiers() & Modifier.STATIC) != 0
24: && (fields[i].getType().equals(Integer.class) || fields[i]
25: .getType().equals(int.class))
26: && fields[i].getInt(null) == value
27: && fields[i].getName().startsWith(prefix)
28: // kind of a hack, but we don't want these two included...
29: && !fields[i].getName().endsWith("_LAST")
30: && !fields[i].getName().endsWith("_FIRST")) {
31: return fields[i].getName();
32: }
33: }
34: } catch (Exception exc) {
35: Log.log(exc);
36: }
37: throw new IllegalArgumentException(
38: "No available field has value " + value);
39: }
40:
41: /** Look up the given static field value. */
42: public static int getFieldValue(Class cls, String fieldName) {
43: try {
44: Field field = cls.getField(fieldName);
45: return field.getInt(null);
46: } catch (Exception exc) {
47: Log.log(exc);
48: // Don't want to ignore these...
49: throw new IllegalArgumentException("No field " + fieldName
50: + " found in " + cls);
51: }
52: }
53: }
|