How to get primitive classes of wrapper classes through reflection?

I am trying to create a new primitive wrapper object through reflection in Java, and I am struggling to get their constructors. I tried to do the same with the String class without any problems (as a performance test, I can, for example, create a String object using the constructor that accepts StringBuilder). See the following code:

try {
    Constructor<?>[] cons = String.class.getConstructors();
    System.out.println(cons + " / " + cons.length);
    Constructor<String> con = String.class.getConstructor(StringBuilder.class);
    String test = con.newInstance(new StringBuilder("argument for StringBuilder"));
    System.out.println(test.getClass().getName() + " : " + test);

    Constructor<?>[] consInteger = Integer.TYPE.getConstructors();
    System.out.println(consInteger + " / " + consInteger.length);

} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

And the result:

[Ljava.lang.reflect.Constructor;@7852e922 / 15
java.lang.String : argument for StringBuilder
[Ljava.lang.reflect.Constructor;@4e25154f / 0

So, when I request the constructors of the String class, I get an Array of 15 constructors. When I request constructors of type Integer, I get an array of 0 elements (no constructors at all).

According to the documentation it has Integer 2 constructor ( Integer(int)and Integer(String)).

? Integer ? Integer.TYPE.getConstructor(String.class), NoSuchMethodException.

+4
2

Integer.TYPE - " , int". int .

Integer.class , .

+4

Integer.class.getConstructors(). Integer.TYPE == int.class.

Integer.valueOf. .

+3

Source: https://habr.com/ru/post/1691616/


All Articles