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 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;
}
else 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 know that there are not so many primitive types 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.
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.