背景:需要在程序运行时或者说某段代码运行后才能知道要创建哪个类的对象。
import java.util.Random;
/**
* @Author: Yeman
* @Date: 2021-10-02-22:18
* @Description:
*/
public class ReflectionTest {
public static Object getInstance(String path) throws Exception {
Class<?> clazz = Class.forName(path); //根据全类名获取类
Object o = clazz.newInstance(); //创建指定运行时类的对象
return o;
}
public static void main(String[] args) {
String path = null;
for (int i = 0; i < 10; i++) {
int c = new Random().nextInt(3); //随机产生0,1,2
//根据产生的情况指定所要创建的类
switch (c){
case 0 :
path = "java.util.Date";
break;
case 1 :
path = "Person";
break;
case 2 :
path = "java.lang.Object";
break;
}
try {
Object instance = getInstance(path);
System.out.println(instance);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}