views:

202

answers:

3

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 'long's. It is easy enough for 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 object.

Any ideas?

+4  A: 

Your using the wrong constant to check for Long primitives - use Long.TYPE, each other primitive type can be found with a like named constnat on the wrapper. Byte.TYPE, Character.TYPE etc.

mP
Perfect! Thats exactly what I was looking for.
macbutch
A: 
o.getClass().getField("fieldName").getType().isPrimitive();
Droo
Yeah I looked at that but I need to know if it is a long primitive not just whether it is a primitive. i.e. match all long primitives but not ints or bytes etc.
macbutch
A: 

You can just use

byte.class
char.class
short.class
float.class
long.class
double.class
void.class

If you are using reflection, why do you care, why do this check at all. The get/set methods always use objects so you don't need to know if the field is a primitive type (unless you try to set a primitive type to the null value.)

In fact, for the method get() you don't need to know which type it is. You can do

// any number type is fine.
Number n = field.get(object);
long l = n.longValue();
Peter Lawrey
Thanks, I didn't know about long.class either.I don't have time to test it but I don't think the rest of your comment applies in my particular case (correct me if I'm wrong. If I do this: Class<?> returnType = m.getReturnType(); if (returnType.equals(Long.class)) { // do stuff }I don't think it will work - I'd still need to check for long.class or Long.TYPE. If I could just call all get...() methods then I could just check what is returned (but I can't do that). Please, let me know if I've misunderstood (likely...).
macbutch
I hope you can read that... I forgot the formatting wouldn't come out. :(
macbutch
try; if (returnType == Long.class || returnType == long.class)
Peter Lawrey