本文共 2556 字,大约阅读时间需要 8 分钟。
通过反射,可以在运行时动态创建类对象。以下是常用的实现方式:
调用类对象的 newInstance 方法,可以Create对象:
User user = (User) c1.newInstance();
如果需要指定构造器参数,可以使用反射API获取指定构造器,并用 newInstance 创建对象:
Constructor con = c1.getDeclaredConstructor(int.class, String.class, int.class);User user = (User) con.newInstance(1, "XXX", 18);
通过反射获取目标方法,然后用 invoke 调用:
Method setName = c1.getDeclaredMethod("setName", String.class);setName.invoke(u, "XXXXX");
如果方法为私有或受访问限制,可以用 setAccessible(true) 激活:
Method getName = c1.getDeclaredMethod("getName");getName.setAccessible(true);long startTime = System.currentTimeMillis();for (int i = 0; i < 1000000000; i++) { getDate.invoke(u); }long endTime = System.currentTimeMillis();System.out.println("花费时间:" + (endTime - startTime) + "ms");
私有属性需要提前设置为可访问:
Field name = c1.getDeclaredField("name");name.setAccessible(true);name.set(u21, "AAAAA");
Method 和 Field 对象都有 setAccessible 方法,其作用是启用或禁用 Java 的访问检查。
如果需要频繁调用反射方法,可以启用:
booleanáfico = true;_name.setAccessible(afectado);invoke方法...
如果需要保持正常检测:
boolean afectado = false;_name.setAccessible(afectado);invoke方法...
setÁc´cеся 布尔值 启用或禁用访问检测
public static void test1() { User u = new User(); long startTime = System.currentTimeMillis(); for (int i = 0; i < 1000000000; i++) { u.getName(); } long endTime = System.currentTimeMillis(); System.out.println("耗时:" + (endTime - startTime) + "ms");}
public static void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { User u = new User(); Method getName = u.getClass().getDeclaredMethod("getName"); long startTime = System.currentTimeMillis(); for (int i = 0; i < 1000000000; i++) { getName.invoke(u); } long endTime = System.currentTimeMillis(); System.out.println("耗时:" + (endTime - startTime) + "ms");}
public static void test3() throws NoSuchMethodException,InvocationTargetException,IllegalAccessException { User u = new User(); Method getName = u.getClass().getDeclaredMethod("getName"); getName.setAccessible(true); long startTime = System.currentTimeMillis(); for (int i = 0; i < 1000000000; i++) { getName.invoke(u); } long endTime = System.currentTimeMillis(); System.out.println("耗时:" + (endTime - startTime) + "ms");}
转载地址:http://oxntz.baihongyu.com/