背景:需要在程序运行时或者说某段代码运行后才能知道要创建哪个类的对象。
import java.util.Random;
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);
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();
}
}
}
}
|