import java.lang.reflect.Constructor; import java.util.Random; public class ReflectionTest { public static void main(String[] args) throws Exception { ClassLoaderTest clt = new ClassLoaderTest(); // 随机创建空参的运行时类对象 for (int i = 0; i < 10; i++) { int num = new Random().nextInt(3);// 0,1,2 String classPath = ""; switch (num) { case 0: classPath = "com.lxh.clazz.Student"; break; case 1: classPath = "java.util.Date"; break; case 2: classPath = "java.lang.Object"; break; } Object instance = clt.getInstance(classPath); System.out.println(instance); } } /* * 创建一个指定类的对象 * classPath:指定类的全类名 */ public Object getInstance(String classPath) throws Exception { Class clazz = Class.forName(classPath); Constructor cons = clazz.getDeclaredConstructor(); return cons.newInstance(); } }
标签:java,String,Object,classPath,动态性,举例,clazz,public From: https://www.cnblogs.com/lxh-daniel/p/16722905.html