Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check type of primitive field

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?

like image 972
macbutch Avatar asked Dec 11 '09 23:12

macbutch


People also ask

How do you know if a field is primitive?

The java. lang. Class. isPrimitive() method can determine if the specified object represents a primitive type.

Is primitive type Java?

Primitive types are the most basic data types available within the Java language. There are 8: boolean , byte , char , short , int , long , float and double . These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose — containing pure, simple values of a kind.

Can you list 8 primitive types in Java?

Primitive data types - includes byte , short , int , long , float , double , boolean and char.


3 Answers

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.

like image 106
mP. Avatar answered Oct 16 '22 08:10

mP.


o.getClass().getField("fieldName").getType().isPrimitive();
like image 25
Droo Avatar answered Oct 16 '22 08:10

Droo


You can just use

boolean.class
byte.class
char.class
short.class
int.class
long.class
float.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();

If you are not sure if it is a Number type you can do

Object o = field.get(object); // will always be an Object or null.
if (o instanceof Number) {
     Number n = (Number) o;
     long l = n.longValue();
like image 41
Peter Lawrey Avatar answered Oct 16 '22 09:10

Peter Lawrey