@Getter
@Setter
@AllArgsConstructor
public class Person {
private Integer age;
private String name;
public static void main(String[] args) {
try {
Person.class.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
结果:
java.lang.InstantiationException:Persion
at java.lang.Class.newInstance(Class.java:427)
at Persion.main(Persion.java:25)
Caused by: java.lang.NoSuchMethodException: Persion.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
... 1 more
原因:因为没有无参构造函数,而 Persion.class.newInstance();只能调用Person的无参构造函数,所以获取无参构造方法失败。
解决:1.加上无参构造方法,在Person类上加上@NoArgsConstructor
2.删除@AllArgsConstructor注解,使用默认无参构造方法。
关于@AllArgsConstructor @Getter @Setter @AllArgsConstructor 注解使用参考:https://blog.csdn.net/m0_38089730/article/details/82736991