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);
            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.

Post a Comment