javareflectionprimitive-types

Determining if an Object is of primitive type


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?


Solution

  • The types in an Object[] will never really be primitive - because you've got references! Here the type of i is int whereas the type of the object referenced by o is Integer (due to auto-boxing).

    It sounds like you need to find out whether the type is a "wrapper for primitive". I don't think there's anything built into the standard libraries for this, but it's easy to code up:

    import java.util.*;
    
    public class Test
    {
        public static void main(String[] args)        
        {
            System.out.println(isWrapperType(String.class));
            System.out.println(isWrapperType(Integer.class));
        }
    
        private static final Set<Class<?>> WRAPPER_TYPES = getWrapperTypes();
    
        public static boolean isWrapperType(Class<?> clazz)
        {
            return WRAPPER_TYPES.contains(clazz);
        }
    
        private static Set<Class<?>> getWrapperTypes()
        {
            Set<Class<?>> ret = new HashSet<Class<?>>();
            ret.add(Boolean.class);
            ret.add(Character.class);
            ret.add(Byte.class);
            ret.add(Short.class);
            ret.add(Integer.class);
            ret.add(Long.class);
            ret.add(Float.class);
            ret.add(Double.class);
            ret.add(Void.class);
            return ret;
        }
    }