Finding the name of a Java object

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.

Technorati Tags: debugging, Java

3 Responses to “Finding the name of a Java object”

  1. Tim Vernum Says:


    Your technique will clearly fail when you have two fields with the same value (well, it will fail, on average 50% of the time), and can fail when used with primitives, but those are probably bearable losses.

    You can avoid the IllegalAccessException by calling setAccessible(true) on the field before using it.
    (Assuming you don’t have an overly zealous SecurityManager installed)

    Having said all of that, I shudder to think of a piece of code that requires such techniques.

  2. Peter Lawrey Says:


    You can also get the fields of the super class.
    You can also look for getters and call those.
    For privative you need to search for the object and use equals() instead of ==
    However for components which have a name I have a Named interface with a getName() method which works fine.
  3. david Says:

    Your technique will clearly fail when you have two fields with the same value (well, it will fail, on average 50% of the time), and can fail when used with primitives, but those are probably bearable losses.

    Yeah, in retrospect I see that … the technique served the purpose I designed it for though.

    I shudder to think of a piece of code that requires such techniques.

    Well, the situation I was in had a single listener being used on multiple widgets in a SWT application. Events were firing when I didn’t expect them and I had to figure out where the event was firing from.

    In my own retrospect, I’m wondering if it wouldn’t make more sense to replace the common listener with individual anonymous inner class listeners that call a common routine.

Leave a Reply

Readers who viewed this page, also viewed:

  • N/A
Close
E-mail It