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 primiti开发者_如何学Gove
}
...
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
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
org.apache.commons.lang.ClassUtils.primitiveToWrapper(Class)
Alternatively, if you're using Guava, it has Primitives class, which you can use like this:
Primitives.wrap(int.class); //returns Class<Integer>
Primitives.wrap(Integer.class); //returns Class<Integer>
Both Guava and Apache Commons use an underlying HashMap<Class<?>, Class<?>>
which isn't really necessary, but makes for readible code.
- Commons Lang3 implementation: org.apache.commons.lang.ClassUtils.primitiveToWrapper
- Guava implementation: com.google.common.primitives.Primitives.wrap
The following über-optimized snippet performs the same functionality in constant time, as it maps to a Wrapper class via an index lookup:
private static final Class[] wrappers = {
Integer.class,
Double.class,
Byte.class,
Boolean.class,
Character.class,
Void.class,
Short.class,
Float.class,
Long.class
};
@SuppressWarnings("unchecked")
public static <T> Class<T> wrap(final Class<T> clazz) {
if (!clazz.isPrimitive()) return clazz;
final String name = clazz.getName();
final int c0 = name.charAt(0);
final int c2 = name.charAt(2);
final int mapper = (c0 + c0 + c0 + 5) & (118 - c2);
return (Class<T>) wrappers[mapper];
}
There is a bit of code golf involved, so don't reorder the classes unless you know what you're doing ;)
精彩评论