java.lang.NoSuchMethodException: userAuth.User.<init>()

我有带有验证的类:

public class User {
    @Size(min=3, max=20, message="User name must be between 3 and 20 characters long")
    @Pattern(regexp="^[a-zA-Z0-9]+$", message="User name must be alphanumeric with no spaces")
    private String name;

    @Size(min=6, max=20, message="Password must be between 6 and 20 characters long")
    @Pattern(regexp="^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$", message="Password must contains at least one number")
    private String password;

    public User(String _name, String _password){
        super();
        name = _name;
        password = _password;
    }

    public String getName(){
        return name;
    }

    public String getPassword(){
        return password;
    }

    public void setPassword(String newPassword){
        password = newPassword;
    }

}

当我验证值时,我收到消息:

SEVERE: Servlet.service() for servlet osAppServlet threw exception
java.lang.NoSuchMethodException: userAuth.User.<init>()

问题出在哪里?


答案 1

该消息表示有人尝试调用没有任何参数的构造函数。添加默认构造函数应该可以解决此问题:java.lang.NoSuchMethodException: userAuth.User.<init>()

public class User {

    public User() {

    }

    ..
}

答案 2

如果 User 类是另一个类(例如 UserAuth)的非静态内部类,则在实例化外部类之前尝试实例化 User 类,则可能会出现消息。在这种情况下,null-arg 构造函数可能存在于代码中,但找不到,因为外部类尚不存在。解决方案可能是将内部类提取到一个独立的类中,使其成为静态的,或者确保外部类的初始化发生在内部类的初始化之前。


推荐