运行反射时报错java.lang.NoSuchMethodException: com.wang.reflect.Student4.<init>()

public class fieldDemo01 {
public static void main(String[] args) throws Exception {
//通过反射获取成员变量并使用
//1、先获取Student类的字节码文件
Class clazz=Student4.class;
//2、通过字节码对象获取构造器对象,然后创建学生类对象
Constructor con=clazz.getConstructor();
Student4 stu=(Student4)con.newInstance();
Student4 stu1=(Student4)clazz.getConstructor().newInstance();//第二种写法 链式编程
//3、设置学生对象的各个属性值
System.out.println(stu);
}
}
class Student4{
public String name;
private int age;

@Override
public String toString() {
return "Student4{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}


Exception in thread "main" java.lang.NoSuchMethodException: com.wang.reflect.Student4.<init>() 这个错误可以通过在Student4类中添加无参构造方法解决

猜你喜欢

转载自www.cnblogs.com/wyj96/p/11928406.html