Is there a way to convert Integer.class
to int.class
, and so on for the rest of primitive types?
Something like:
jshell> Boolean.class.isPrimitive()
$1 ==> false
jshell> Boolean.class.asPrimitive() == boolean.class
$2 ==> true
Is there a way to convert Integer.class
to int.class
, and so on for the rest of primitive types?
Something like:
jshell> Boolean.class.isPrimitive()
$1 ==> false
jshell> Boolean.class.asPrimitive() == boolean.class
$2 ==> true
It's possible to do this with ClassUtils
from commons-lang:
jshell> import org.apache.commons.lang3.ClassUtils
jshell> ClassUtils.primitiveToWrapper(int.class)
$1 ==> class java.lang.Integer
jshell> ClassUtils.wrapperToPrimitive(Float.class)
$2 ==> float
There is no Java SE method for it, but it’s easy to keep a Map:
private static final Map<Class<?>, Class<?>> wrapperToPrimitive = Map.of(
Void.class, void.class,
Boolean.class, boolean.class,
Byte.class, byte.class,
Character.class, char.class,
Short.class, short.class,
Integer.class, int.class,
Long.class, long.class,
Float.class, float.class,
Double.class, double.class);