Savvas Dalkitsis Savvas Dalkitsis - 1 year ago 58
Java Question

Simple way to get wrapper class type in Java

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 only and not primitives. I want an easy way of determining if a Field's type is primitive and swap it with the appropriate wrapper class. So in code what i do so far is something like this :

Field f = getTheField(); // Dummy method that returns my Field
Class<?> c = f.getType();
if (c == int.class)
c = Integer.class;
if (c == float.class)
c = Float.class;
// etc

This works fine except for the fact that i need to explicitly check for all the primitive types and swap them with the appropriate wrapper class. Now i now that they are not so many and it won't be a problem to simply list them all but i was wondering if there was an easier and more elegant way of doing it.

Answer Source

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>
  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)

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download