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?
I think this happens due to auto-boxing.
You may implement a utility method that matches these specific boxing classes and gives you if a certain class is primitive.
Get ahold of BeanUtils from Spring http://static.springsource.org/spring/docs/3.0.x/javadoc-api/
Probably the Apache variation (commons beans) has similar functionality.
For those who like terse code.
As several people have already said, this is due to autoboxing.
You could create a utility method to check whether the object's class is
Integer
,Double
, etc. But there is no way to know whether an object was created by autoboxing a primitive; once it's boxed, it looks just like an object created explicitly.So unless you know for sure that your array will never contain a wrapper class without autoboxing, there is no real solution.
Just so you can see that is is possible for isPrimitive to return true (since you have enough answers showing you why it is false):
This matters in reflection when a method takes in "int" rather than an "Integer".
This code works:
This code fails (cannot find the method):