Why we need isPrimitive() in the first place?

Hearen :

Sorry for the unclear question but I am truly lost why we need isPrimitive() in the first place since I cannot use it (sorry I just cannot use it when I need it ;( sad face here).

After reading posts here and there, I found somes usages as

int.class.isPrimitive()

But I'd like to have something as

boolean isTrue = true;
System.out.println(isTrue.class.isPrimitive());
System.out.println(Boolean.valueOf(isTrue).getClass().isPrimitive());

I am trying to check the types while traversing the fields of an object; what I can do now is to

private static boolean isPrimitiveWrapper(Object obj) {
    return obj.getClass() == Boolean.class ||
            obj.getClass() == Byte.class ||
            obj.getClass() == Character.class ||
            obj.getClass() == Short.class ||
            obj.getClass() == Integer.class ||
            obj.getClass() == Long.class ||
            obj.getClass() == Float.class ||
            obj.getClass() == Double.class;
}

But after checking around, I think there should be something wrong with it but I don't know what it is.

Any use cases for that will be really appreciated ;)

I am trying to be not too paranoid...trying pretty hard already

Joop Eggen :

As the primitive types cannot be dealt with as Object in some cases, like arrays, it is nice as first discriminator.

Object cloneObject(Object obj) {
    Class<?> type = obj == null ? Object.class : obj.getClass();
    if (type.isArray()) {
        Class<?> elemType = type.getComponentType();
        if (!elemType.isPrimitive()) {
            Object[] copy = ...
        } else {
            // Must distinguish between int/double/boolean/...
            ... int[] ... double[] ...
        }
    }

Object inta = new int[] { 2, 3, 5, 7 };
int[] pr = (int[]) cloneObject(inta);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86178&siteId=1