Check type of primitive field

macbutch picture macbutch · Dec 12, 2009 · Viewed 66.7k times · Source

I'm trying to determine the type of a field on an object. I don't know the type of the object when it is passed to me but I need to find fields which are longs. It is easy enough to distinguish the boxed Longs but the primitive long seems more difficult.

I can make sure that the objects passed to me only have Longs, not the primitives, but I'd rather not. So what I have is:

for (Field f : o.getClass().getDeclaredFields()) {
    Class<?> clazz = f.getType();
    if (clazz.equals(Long.class)) {
        // found one -- I don't get here for primitive longs
    }
}

A hacky way, which seems to work, is this:

for (Field f : o.getClass().getDeclaredFields()) {
    Class<?> clazz = f.getType();
    if (clazz.equals(Long.class) ||  clazz.getName().equals("long")) {
        // found one
    }
}

I'd really like a cleaner way to do this if there is one. If there is no better way then I think that requiring the objects I receive to only use Long (not long) would be a better API.

Any ideas?

Answer

mP. picture mP. · Dec 12, 2009

You're using the wrong constant to check for Long primitives - use Long.TYPE, each other primitive type can be found with a similarly named constant on the wrapper. eg: Byte.TYPE, Character.TYPE, etc.