Close

Java Reflection - How to find out by reflection that a primitive class is assignable to/from its corresponding wrapper class?

Java Reflection Java 

Class.isAssignable() returns false if we use it for a primitive class and pass its corresponding wrapper class (or vice-versa). They are, in fact, assignable to each other via auto boxing/unboxing.
Following utility method isAssignableTo() can handle that case too.

import java.util.Map;

public class ReflectUtil {
private static final Map<Class<?>, Class<?>> primitiveWrapperMap =
Map.of(boolean.class, Boolean.class,
byte.class, Byte.class,
char.class, Character.class,
double.class, Double.class,
float.class, Float.class,
int.class, Integer.class,
long.class, Long.class,
short.class, Short.class);

public static boolean isPrimitiveWrapperOf(Class<?> targetClass, Class<?> primitive) {
if (!primitive.isPrimitive()) {
throw new IllegalArgumentException("First argument has to be primitive type");
}
return primitiveWrapperMap.get(primitive) == targetClass;
}

private static boolean isAssignableTo(Class<?> from, Class<?> to) {
if (to.isAssignableFrom(from)) {
return true;
}
if (from.isPrimitive()) {
return isPrimitiveWrapperOf(to, from);
}
if (to.isPrimitive()) {
return isPrimitiveWrapperOf(from, to);
}
return false;
}

public static void main(String[] args) {
boolean b = boolean.class.isAssignableFrom(Boolean.class);
System.out.println(b);
b = Boolean.class.isAssignableFrom(boolean.class);
System.out.println(b);
b = isAssignableTo(boolean.class, Boolean.class);
System.out.println(b);
b = isAssignableTo(Boolean.class, boolean.class);
System.out.println(b);
}
}

[JDK 9]

Output

false
false
true
true




See Also