Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get primitive wrapper classes constructors via reflection?

Tags:

java

I am trying to create a new primitive wrapper object via reflection in Java and I struggle to get the constructors of them. I tried to do the same thing with a String class without problems (as a sanity test, I can for example create a String object using constructor that accepts a StringBuilder) Please see the code below:

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 output is:

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

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

According to documentation Integer has 2 constructors (Integer(int) and Integer(String)).

What is the problem? How can I get a constructor for Integer type using reflection? When I try to use Integer.TYPE.getConstructor(String.class) I get a NoSuchMethodException.

like image 481
hippieSabotage89 Avatar asked Mar 08 '23 05:03

hippieSabotage89


2 Answers

Integer.TYPE is "The Class instance representing the primitive type int." int has no constructors.

Use Integer.class to refer to the wrapper class, which does.

like image 126
John Kugelman Avatar answered Apr 05 '23 23:04

John Kugelman


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

However you might prefer Integer.valueOf. For the caching of Integers.

like image 25
Joop Eggen Avatar answered Apr 05 '23 22:04

Joop Eggen