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?
Starting in Java 1.5 and up, there is a new feature called auto-boxing. The compiler does this itself. When it sees an opportunity, it converts a primitive type into its appropriate wrapper class.
What is probably happening here is when you declare
The compiler will compile this statement as saying
This is auto-boxing. This would explain the output you are receiving. This page from the Java 1.5 spec explains auto-boxing more in detail.
Google's Guava library has a Primitives utility that check if a class is a wrapper type for a primitive: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/primitives/Primitives.html
Class.isPrimitive() works for primitives
This is the simplest way I could think of. The wrapper classes are present only in
java.lang
package. And apart from the wrapper classes, no other class injava.lang
has field namedTYPE
. You could use that to check whether a class is Wrapper class or not.you could determine if an object is wrapper type by beneath statements:
and you could also determine a primitive object by using the isPrimitive() method