I just discovered a technique that’s quite handy … at work I’m writing some java code that uses a lot of generic methods. The problem is, it’s quite difficult to figure out what actual field name in the java code is being referenced by the code (it’s being triggered by one or more events).
After digging around a bit, I created a little routine that will return the NAME of the field that a particular object represents.
private String getFieldName(Object o) { String name = "unknown"; Field[] fields = getClass().getDeclaredFields(); try { for (int i=0;i<fields.length;i++) { Field f = fields[i]; Object v = f.get(this); if (o == v) { name = f.getName(); break; } } } catch (Exception e) { name = e.getMessage(); } return name; }
Obviously I’m not sure this will work in 100% of the time, but it seems to work for me now.
One thing to note, however, the routine MUST be in the consuming class … it can’t be in a super class, as the f.get(this) call will result in a IllegalAccessException.
Recent Comments