通过反射创建对象的两种方法
1.通过Class字节码对象newInstance();(默认通过无参构造创建)
2.通过获取构造器getConstructor(Class<?>..parameterTypes);(通过有参的构造器,参数可以指定具体类型和多个数量)
代码:
假设我们有一个用户类User
package test.java.zxj.test_project;
public class User {
private String userId;
private String name;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
此时没有自定义构造参数,只有默认的无参构造;
通过反射可以直接创建对象
package test.java.zxj.test_project;
public class TestReflection {
public static void main(String[] args) throws Exception {
Class<?> clz = Class.forName("test.java.zxj.test_project.User");
Object object = clz.newInstance();
System.out.println(object instanceof User);
}
}
打印结果为true;
这种clz.newInstance()的方式,只能创建默认无参构造的对象;
对于有参构造的对象怎么创建呢?
还是这个User,我们加上带参数的构造;
package test.java.zxj.test_project;
public class User {
private String userId;
private String name;
public User() {
}
public User(String userId, String name) {
super();
this.userId = userId;
this.name = name;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
这时候我们需要通过获取构造器,来创建对象:
package test.java.zxj.test_project;
import java.lang.reflect.Constructor;
public class TestReflection {
public static void main(String[] args) throws Exception {
Class<?> clz = Class.forName("test.java.zxj.test_project.User");
//获取参数为<String,String>的构造器
Constructor<?> constructor = clz.getConstructor(String.class, String.class);
Object object = constructor.newInstance("userId_001","name_jack");
// System.out.println(object instanceof User);
if (object instanceof User) {
User user = (User)object;
System.out.println("userId:" + user.getUserId());
System.out.println("name:" + user.getName());
}
}
}
可以打印出结果
userId:userId_001
name:name_jack
注意:这里获取构造器只能获取public的,对于私有的需要暴力反射
constructor.setAccessible(true);