Skip to content

On reflection and type inference in Java

22 September 2010

It happens. Sometimes you just have to write ugly code.

As an example, you may find out that the private field you really need in your web framework (yes Richfaces, I’m talking to you) is really unaccessible.

There are tons of examples on the internet on how to access private fields, just set the setAccessible property of the Field class to true and then call get.

Since I have to extrapolate data from two or three classes, I decided to write a simple helper function to do it.

import java.lang.reflect.Field;

public class ReflectionUtils {
    @SuppressWarnings("unchecked")
    public static <T> T getPrivateField(final Class clazzFrom, final String fieldName, final Object objFrom) throws NoSuchFieldException, IllegalAccessException {
        final Field tag = clazzFrom.getDeclaredField(fieldName);
        tag.setAccessible(true);
        return (T) tag.get(objFrom);
    }
}

What is the cool (and different from the others) thing about this method? It is in the type signature

static <T> T getPrivateField.

Java simply infers the return value type from the type of the variable, So that you can use it like this:

import static ReflectionUtils.getPrivateField;

final ValueExpressionImpl orig = getPrivateField(TagValueExpression.class, "orig", expression);

Sometimes even ugly code can become pretty!

Advertisements

From → Programming

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: