I have an Object[]
array, and I am trying to find the ones that are primitives. I've tried to use Class.isPrimitive()
, but it seems I'm doing something wrong:
int i = 3;
Object o = i;
System.out.println(o.getClass().getName() + ", " +
o.getClass().isPrimitive());
prints java.lang.Integer, false
.
Is there a right way or some alternative?
Integer
is not a primitive,Class.isPrimitive()
is not lying.I'm late to the show, but if you're testing a field, you can use
getGenericType
:The Oracle docs list the 8 primitive types.
The types in an
Object[]
will never really be primitive - because you've got references! Here the type ofi
isint
whereas the type of the object referenced byo
isInteger
(due to auto-boxing).It sounds like you need to find out whether the type is "wrapper for primitive". I don't think there's anything built into the standard libraries for this, but it's easy to code up:
commons-lang
ClassUtils
has relevant methods. The new version has:The old versions have
wrapperToPrimitive(clazz)
method, which will return the primitive correspondence. So you can do:You have to deal with the auto-boxing of java.
You get the class test.class and javap -c test let's you inspect the generated bytecode. As you can see the java compiler added to create a new Integer from your int and then stores that new Object in o via astore_2Let's take the code
The primitve wrapper types will not respond to this value. This is for class representation of primitives, though aside from reflection I can't think of too many uses for it offhand. So, for example
prints "false", but
prints "true"