views:

57

answers:

1

Hi

is there an easy in Java to convert primitive class objects into object class objects? Given a class Class cl, I want to convert it into a Class that has no primitives. Eg.

Class<?> cl = int.class;

...
if (cl.isPrimitive()) {
  cl = Object of primitive
}
...

cl == Integer.class

I would like a method that does that for all primitive types. Obviously I could iterate through all primitive types, but I thought someone may know about a better solution.

Cheers, Max

+1  A: 

Hope I understood it right. Basically you want a mapping from primitive class types to their wrapper methods.

A static utility method implemented in some Utility class would be an elegant solution, because you would use the conversion like this:

Class<?> wrapper = convertToWrapper(int.class);

Alternativly, declare and populate a static map:

public final static Map<Class<?>, Class<?>> map = new HashMap<Class<?>, Class<?>>();
static {
    map.put(boolean.class, Boolean.class);
    map.put(byte.class, Byte.class);
    map.put(short.class, Short.class);
    map.put(char.class, Char.class);
    map.put(int.class, Integer.class);
    map.put(long.class, Long.class);
    map.put(float.class, Float.class);
    map.put(double.class, Double.class);
}

private Class<?> clazz = map.get(int.class);  // usage
Andreas_D
Yes, that's pretty much how I ended up doing it. Thanks for that.
Max