Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Convert Primitive Class [duplicate]

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

like image 798
Max Avatar asked Aug 13 '10 03:08

Max


2 Answers

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

Alternatively, 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, Character.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
like image 143
Andreas Dolk Avatar answered Oct 05 '22 00:10

Andreas Dolk


org.apache.commons.lang.ClassUtils.primitiveToWrapper(Class)

like image 44
agad Avatar answered Oct 05 '22 01:10

agad