Java类如果定义了有参构造函数没有无参构造函数,用 class.newInstance()会报异常java.lang.InstantiationException

@Getter
@Setter
@AllArgsConstructor
public class Persion {

    private Integer age;

    private String name;

    public static void main(String[] args) {
        try {
            Persion.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.()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.newInstance(Class.java:412)
    ... 1 more

原因:因为没有无参构造函数,而 Persion.class.newInstance();只能调用Person的无参构造函数,所以获取无参构造方法失败。

解决:1.加上无参构造方法,在Persion类上加上@NoArgsConstructor

2.删除@AllArgsConstructor注解,使用默认无参构造方法。

关于@AllArgsConstructor @Getter @Setter @AllArgsConstructor 注解使用参考:https://blog.csdn.net/m0_38089730/article/details/82736991

 

你可能感兴趣的:(java)