Class PersonC = Person.class; /* * 调用newInstance的条件: * 1 对应的类要提供空参构造器 * 2 空参构造器的访问权限应为public * * * */ Object p = PersonC.newInstance(); System.out.println(p);
通过运行时类,可以动态创建不同的类:
int num = new Random().nextInt(3); String classPath = null; switch (num){ case 0: classPath = "java.util.Data"; break; case 1: classPath = "java.lang.Object"; break; case 2: classPath = "com.LearnJava.reflect.Person"; break; } try { System.out.println(getInstance(classPath)); } catch (Exception e) { e.printStackTrace(); } } public static Object getInstance (String classPath)throws Exception{ Class cl = Class.forName(classPath); return cl.newInstance(); }