我今天写代码发现了问题
Exception in thread "main" java.lang.NoSuchMethodException: com.fan.model.User.<init>(int, java.lang.String, java.lang.String)
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at com.fan.reflect.获得一个构造方法并创建对象.main(获得一个构造方法并创建对象.java:19)
进程已结束,退出代码1
我的代码:
package com.fan.reflect;
import com.fan.model.User;
import java.lang.reflect.Constructor;
public class 获得一个构造方法并创建对象 {
public static void main(String[] args) throws Exception{
Class<User> userClass = User.class;
Constructor<User> declaredConstructor = userClass.getDeclaredConstructor(int.class, String.class, String.class);
User user = declaredConstructor.newInstance(11, "樊军刚", "123456");
System.out.println(user);
}
}
package com.fan.model;
public class User {
private Integer user_id;
public String user_name;
private String user_password;
public User(Integer user_id, String user_name, String user_password) {
this.user_id = user_id;
this.user_name = user_name;
this.user_password = user_password;
}
public User() {
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
@Override
public String toString() {
return "User{" +
"user_id=" + user_id +
", user_name='" + user_name + '\'' +
", user_password='" + user_password + '\'' +
'}';
}
}
我的问题出在了我那个获取有参数的构造方法
Constructor<User> declaredConstructor = userClass.getDeclaredConstructor(int.class, String.class, String.class);
和 User类中的有参构造类型不匹配
public User(Integer user_id, String user_name, String user_password) {
this.user_id = user_id;
this.user_name = user_name;
this.user_password = user_password;
}
在反射中用构造函数创建对象时,那个调用newInstance时的有参列表必须和那个实体类的有参列表类型一致,顺序一致! 即便是int和Integer也要分的清楚,不能互相替代!
|