Simple way to get wrapper class type in Java

前端 未结 9 1454
天命终不由人
天命终不由人 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
      @SuppressWarnings("unchecked")
      private static  Class wrap(Class c) {
        return c.isPrimitive() ? (Class) PRIMITIVES_TO_WRAPPERS.get(c) : c;
      }
    
      private static final Map, Class> PRIMITIVES_TO_WRAPPERS
        = new ImmutableMap.Builder, 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.

提交回复
热议问题