栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用Constructor获取带参构造时出现java.lang.NoSuchMethodException异常

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Constructor获取带参构造时出现java.lang.NoSuchMethodException异常

使用Constructor获取带参构造时出现java.lang.NoSuchMethodException异常

使用如下代码获取Cat类的带参构造时出现了java.lang.NoSuchMethodException异常

Properties properties = new Properties();
properties.load(
    new FileInputStream("src/com/csdn/reflect/pojo/Properties.properties"));
String bean =  properties.getProperty("bean");
Class c = Class.forName(bean);
Constructor cons = c.getDeclaredConstructor(Integer.class, String.class);

Cat类:

public class Cat {
    private int id;
    private String name;

    public Cat() {
    }

    public Cat(int id, String name) {
        this.id = id;
        this.name = name;
    }

经检查后发现是参数类型指定有问题,在使用Constructor获取带参构造时,引用类型与基本类型不能混用,也就是说构造方法需要int类型,而获取时传入的是Integer类型,所以找不到构造方法,将Integer.class改为int.class编译通过

Properties properties = new Properties();
properties.load(
    new FileInputStream("src/com/csdn/reflect/pojo/Properties.properties"));
String bean =  properties.getProperty("bean");
Class c = Class.forName(bean);
Constructor cons = c.getDeclaredConstructor(int.class, String.class);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/855021.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号