如何将 Integer.class (和其他盒装)转换为 int.class (和其他基元)?

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

有没有办法将 Integer.class 转换为 int.class,其余原始类型依此类推?

类似于:

jshell> Boolean.class.isPrimitive()
 ==> false
jshell> Boolean.class.asPrimitive() == boolean.class
 ==> true

没有Java SE 方法,但很容易保留地图:

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

可以通过 commons-lang 中的 ClassUtils 来做到这一点:

jshell> import org.apache.commons.lang3.ClassUtils

jshell> ClassUtils.primitiveToWrapper(int.class)
 ==> class java.lang.Integer

jshell> ClassUtils.wrapperToPrimitive(Float.class)
 ==> float