Determining if an Object is of primitive type

2019-01-01 15:13发布

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?

17条回答
梦该遗忘
2楼-- · 2019-01-01 15:46

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

Object o = i;

The compiler will compile this statement as saying

Object o = Integer.valueOf(i);

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.

查看更多
怪性笑人.
3楼-- · 2019-01-01 15:48
public class CheckPrimitve {
    public static void main(String[] args) {
        int i = 3;
        Object o = i;
        System.out.println(o.getClass().getSimpleName().equals("Integer"));
        Field[] fields = o.getClass().getFields();
        for(Field field:fields) {
            System.out.println(field.getType());
        }
    }
}  

Output:
true
int
int
class java.lang.Class
int
查看更多
唯独是你
4楼-- · 2019-01-01 15:51

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

Primitives.isWrapperType(class)

Class.isPrimitive() works for primitives

查看更多
余生请多指教
5楼-- · 2019-01-01 15:52

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 in java.lang has field named TYPE. You could use that to check whether a class is Wrapper class or not.

public static boolean isBoxingClass(Class<?> clazz)
{
    String pack = clazz.getPackage().getName();
    if(!"java.lang".equals(pack)) 
        return false;
    try 
    {
        clazz.getField("TYPE");
    } 
    catch (NoSuchFieldException e) 
    {
        return false;
    }           
    return true;        
}
查看更多
时光乱了年华
6楼-- · 2019-01-01 15:53

you could determine if an object is wrapper type by beneath statements:

***objClass.isAssignableFrom(Number.class);***

and you could also determine a primitive object by using the isPrimitive() method

查看更多
登录 后发表回答