简体   繁体   中英

How to get primitive wrapper classes constructors via reflection?

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 .

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM