Friday, June 09, 2006

Finding a field in Java

A large motivation for me starting this blog was to help me remember useful snippets of code. This is a good example:

Field getField(Class clazz, final String fieldName)
        throws NoSuchFieldException {
    for (; null != clazz; clazz = clazz.getSuperclass()) {
        try {
            final Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (final NoSuchFieldException e) { }
    }

    throw new NoSuchFieldException(fieldName);
}

Very simple code, no? But a fact I seem to sometime forget is that inherited fields do not show up in reflection; one must reflect down into the appropriate superclass where the field was declared. The simple method handles the details easily enough.

1 comment:

Anonymous said...

Useful if you want to find a field which is not public. But I guess this is your aim, since you added the command setAccessible(true). For public fields, the Class.getField(name) is enough.