You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Java反射获取基本类型包装类的构造器?

哦,这个问题我太熟悉了!你踩了一个很容易混淆的Java反射坑——把Integer.TYPE和Integer.class搞混啦!

问题出在哪?

你代码里的Integer.TYPE其实是基本类型int的Class对象,而不是java.lang.Integer包装类的Class对象。基本类型本身根本没有构造器,所以调用getConstructors()返回0个结果是完全正常的。

反观你测试的String.class,它就是字符串类本身的Class对象,自然能拿到它所有的公共构造器,这也是为什么String的测试代码能正常跑通。

怎么解决?

要获取Integer包装类的构造器,你需要用Integer.class来获取正确的Class对象。下面是修正后的完整代码:

try {
    // String测试部分保持不变
    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);
    
    // 关键修正:用Integer.class替代Integer.TYPE
    Constructor<?>[] consInteger = Integer.class.getConstructors();
    System.out.println(consInteger + " / " + consInteger.length);
    
    // 现在可以正常获取Integer(String)构造器并创建实例了
    Constructor<Integer> integerCon = Integer.class.getConstructor(String.class);
    Integer num = integerCon.newInstance("123");
    System.out.println(num.getClass().getName() + " : " + num);
} catch (Exception e) {
    e.printStackTrace();
}
额外小知识

所有基本类型的包装类都有一个TYPE字段,对应的是它们关联的基本类型的Class对象:

  • Long.TYPE → long.class
  • Boolean.TYPE → boolean.class
  • Double.TYPE → double.class
    以此类推。如果要通过反射操作包装类,一定要用包装类本身的class对象,而不是TYPE字段。

内容的提问来源于stack exchange,提问作者hippieSabotage89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:51:11