使用如下代码获取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);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)