通过反射,创建对应的运行时类的对象
package com.atguigu.java;
import org.junit.Test;
import java.util.Random;
/**
* 通过反射,创建对应的运行时类的对象
*
* @author liangqichen
* @create 2021-10-28 15:50
*/
public class NewInstanceTest {
@Test
public void test1() throws InstantiationException, IllegalAccessException {
Class<Person> clazz = Person.class;
/*
newInstance(): 调用此方法,创建对应的运行时类的对象
内部调用运行时类的空参构造器
要想此方法正常的创建运行时类的对象,要求:
1.运行时类必须提供空参的构造器
2.空参的构造器的访问权限适当。通常设置为public的
在javabean中,要求提供一个public的空参构造器。原因:
1.便于通过反射创建运行时类的对象
2.便于子类继承运行时类时,默认调用super()时,保证父类有此构造器
*/
Person obj = (Person) clazz.newInstance();
System.out.println(obj); // Person{name='null', age=0}
}
// 体会反射的动态性
@Test
public void test2() {
for (int i = 0; i < 100; i++) {
int number = new Random().nextInt(3); // 0 1 2
String classPath = "";
switch (number) {
case 0:
classPath = "java.util.Date";
break;
case 1:
classPath = "java.lang.Object";
break;
case 2:
classPath = "com.atguigu.java.Person";
break;
}
try {
Object obj = getInstance(classPath);
System.out.println(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
此方法,创建一个指定类的对象。
classPath:指定类的全类名
*/
public Object getInstance(String classPath) throws Exception {
Class clazz = Class.forName(classPath);
return clazz.newInstance();
}
}