Search code examples
javaprimitive-types

How to convert Integer.class (and other boxed) to int.class (and other primitives)?


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

Solution

  • 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