比如,我们要创建哪个类的对象,编译的时候是确定不下来的,只有在运行的时候才能确定下来。这也就体现了反射的动态性。
下面的代码,使用Random类,产生[0, 3)的随机数,已验证反射的动态性。
public class DynamicTest {
/**
* 创建一个指定类的对象
* @param classPath 指定类的全类名
* @return 返回一个指定类的对象
*/
public static Object getInstance(String classPath) throws Exception {
Class clazz = Class.forName(classPath);
return clazz.newInstance();
}
public static void main(String[] args) {
int number;
String classPath = "";
for (int i = 0; i < 100; i++) {
number = new Random().nextInt(3); // 0 1 2
switch(number) {
case 0:
classPath = "com.cenyu.pojo.Person";
break;
case 1:
classPath = "java.lang.String";
break;
case 2:
classPath = "java.util.Date";
break;
}
try {
Object obj = getInstance(classPath);
System.out.println(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}