This tiny class sped up my reflection stuff by a factor of 3 (minimum!).
The idea behind: avoid the costly .getField() by hashing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import java.lang.reflect.Field; import java.util.HashMap;
public class FieldHash extends HashMap<Class, HashMap<String, Field>> { public Field getField(Class c, String fieldname) throws SecurityException, NoSuchFieldException { HashMap<String, Field> h = get(c); if (h == null) { put(c, h = new HashMap()); } Field f = h.get(fieldname); if (f == null) { h.put(fieldname, f = c.getField(fieldname)); } return f; } } |
1
| fieldhash.getField(myclass,"myvariable"); |
is about 25x

faster than
1
| myclass.getField("myvariable"); |