2

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
andreoss
  • 1,570
  • 1
  • 10
  • 25
  • first thing `int` is not a class it is a primitive and java will automatically conver this using concept called autoboxing and unboxing – deadshot Jul 09 '20 at 03:00
  • I'm asking about `int.class` which is a `Class` – andreoss Jul 09 '20 at 03:03
  • this will helo you understand what is `Integer.class` and `int.class` https://stackoverflow.com/questions/22470985/integer-class-vs-int-class – deadshot Jul 09 '20 at 03:05
  • No. You have to make your own `Map` of wrapper classes to primitive types. – VGR Jul 09 '20 at 03:09
  • I'm afraid you will need to be more clear about what you mean when you say "convert Integer.class to int.class". What are you trying to do specifically? Note that, when you use reflection, even if a field or method parameter is of type "int.class", the value you obtain for the field or pass to the parameter via reflection is still a wrapper (i.e. Integer.class) – Marcio Lucca Jul 09 '20 at 03:15
  • @MarcioLucca I have a dictionary type structure where I can get and save a value with a string key and a class tag. I want it to behave in the same manner for `int.class` and `Integer.class`, i.e (`dict.get('foo", int.class)` is the same as `dict.get("foo", Integer.class)` – andreoss Jul 09 '20 at 03:20
  • In that case I'm afraid there is no way to convert, you would have to test for both types individually: ``` Class> cls = dict.get("foo"); if (cls == int.class || cls == Integer.class) { // do common behavior } ``` – Marcio Lucca Jul 09 '20 at 03:42

2 Answers2

2

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
andreoss
  • 1,570
  • 1
  • 10
  • 25
1

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);
VGR
  • 40,506
  • 4
  • 48
  • 63