views:

161

answers:

3

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
myMethod(c);

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.

+3  A: 

You can call class.isPrimitive() to know if it is a primitive or not, however, there is no boxing method to convert the classes within the JDK. There is at least one open bug relating to this.

Yishai
+6  A: 

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://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/primitives/Primitives.html

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

Kevin Bourrillion
So basically same thing... :) Thanks for the answer. Basically there is no other way at the moment.
Savvas Dalkitsis
+3  A: 

Apache Commons Lang has a utility method to do this (ClassUtils.primitiveToWrapper()), which will be just as ugly under the covers, but at least you can pretend it's nice.

skaffman
Almost +1 for "at least you can pretend it's nice". :)
Software Monkey