Simple way to get wrapper class type in Java

前端 未结 9 1437
天命终不由人
天命终不由人 2020-11-29 09:14

I have a piece of code where I need to pass the class of a field in a method. Because of the mechanics of my code I can only handle reference objects and not primitives. I w

相关标签:
9条回答
  • 2020-11-29 09:50

    I use Google Collections Library in my answer, because I'm spoiled like that, but you can probably see how to do it with plain HashMaps if you prefer.

      // safe because both Long.class and long.class are of type Class<Long>
      @SuppressWarnings("unchecked")
      private static <T> Class<T> wrap(Class<T> c) {
        return c.isPrimitive() ? (Class<T>) PRIMITIVES_TO_WRAPPERS.get(c) : c;
      }
    
      private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS
        = new ImmutableMap.Builder<Class<?>, Class<?>>()
          .put(boolean.class, Boolean.class)
          .put(byte.class, Byte.class)
          .put(char.class, Character.class)
          .put(double.class, Double.class)
          .put(float.class, Float.class)
          .put(int.class, Integer.class)
          .put(long.class, Long.class)
          .put(short.class, Short.class)
          .put(void.class, Void.class)
          .build();
    

    It is odd that nothing exists in the JDK for this, but indeed nothing does.

    EDIT: I'd totally forgotten that we released this:

    http://google.github.io/guava/releases/21.0/api/docs/com/google/common/primitives/Primitives.html

    It has the wrap() method, plus unwrap() and a few other incidental things.

    0 讨论(0)
  • 2020-11-29 09:53

    Here is another way if you don't need highly optimized code:

        Class<?> primitive=long.class;
        Class<?> boxed=Array.get(Array.newInstance(primitive,1),0).getClass();
        System.out.println(primitive.getName());
        System.out.println(boxed.getName());
    

    (Editing/adding explanation)

    At first, it was to see if Java has a method to give you the wrapper class when given a primitive type. Couldn't find any.

    Then, it was to see if you can have Java create a primitive value when give a primitive type (then you can somehow get an object out of it). Couldn't find a way to do this.

    But then it was found out that you CAN have Java create an array of primitive values when given a primitive type. And then there is a Java method that gives you an object of the wrapping type of the array element(which is primitive). Once you have the object, you can then get the type.

    So here is how the whole thing work:

    The method Array.newInstance() creates a array of whatever type you specify, whether it is primitive or object. In the case of object, all elements are object type but initialized to null. In the case of primitive, elements are primitive type. But primitive variable/array element can't be null, so they have the default value of the primitive type, e.g. int will be zero. Thus no elements will be null. And now if you try to get the value of an element by using Array.get(), Array.get() has no choice but box that primitive value to an object, e.g. int to Integer, because Array.get() can't return primitive value. Now you have an object of the boxing(wrapping) type of you original primitive type. Finally calling Object.getClass() gives you the boxing(wrapping) type.

    This trick works with any primitive type you have in Java today and in the future.

    0 讨论(0)
  • 2020-11-29 09:54
    Class<?> toWrapper(Class<?> clazz) {
        if (!clazz.isPrimitive())
            return clazz;
    
        if (clazz == Integer.TYPE)
            return Integer.class;
        if (clazz == Long.TYPE)
            return Long.class;
        if (clazz == Boolean.TYPE)
            return Boolean.class;
        if (clazz == Byte.TYPE)
            return Byte.class;
        if (clazz == Character.TYPE)
            return Character.class;
        if (clazz == Float.TYPE)
            return Float.class;
        if (clazz == Double.TYPE)
            return Double.class;
        if (clazz == Short.TYPE)
            return Short.class;
        if (clazz == Void.TYPE)
            return Void.class;
    
        return clazz;
    }
    
    0 讨论(0)
提交回复
热议问题