java.lang.NoSuchMethodException: com.lkyyy.test02.Student.(com.lkyyy.test02.Student)
at java.base/java.lang.Class.getConstructor0(Class.java:3349)
at java.base/java.lang.Class.getConstructor(Class.java:2151)
at com.lkyyy.test02.fanshe.main(fanshe.java:20)
Process finished with exit code 0
getConstructor()参数错误
无参和有参构造函数
public Student() {
System.out.println("???????");
}
public Student(String name) {
System.out.println("姓名是"+name);
}
调用方式
Class<?> stuClass3 = Class.forName("com.lkyyy.test02.Student");
//注意此字符串必须是真实路径,就是带包名的类路径,包名.类名
Constructor constructor = stuClass3.getConstructor(String.class);
//getConstructor()所带参数为需要使用反射机制的类的有参构造函数的参数的class文件,
//或者使用无参构造函数
使用无参构造函数
Class<?> stuClass3 = Class.forName("com.lkyyy.test02.Student");
Constructor constructor = stuClass3.getConstructor();
Object o = constructor.newInstance();
Student oo = (Student) o;
oo.shot();
输出结果
使用有参构造函数;
Class<?> stuClass3 = Class.forName("com.lkyyy.test02.Student");
Constructor constructor = stuClass3.getConstructor(String.class);
Object o = constructor.newInstance("小明");
Student oo = (Student) o;
oo.shot();
输出结果
当我们使用getConstructor获取的是有参构造函数时,在使用newInstance方法时不带参数时不会有提醒,会在运行时出现java.lang.IllegalArgumentException:异常