测试代码如下:
package Collections; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class text3 { //普通方式调用 public static void text1() { person user = new person(); long startTime = System.currentTimeMillis(); for (int i = 0; i < 1000000000; i++) { user.getName(); } long endTime = System.currentTimeMillis(); System.out.println("普通方式执行10亿次;" + (endTime - startTime) + "ms"); } //通过反射的方式调用 public static void text2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { person user = new person(); Class c = user.getClass(); Method getName = c.getDeclaredMethod("getName", null); long startTime = System.currentTimeMillis(); for (int i = 0; i < 1000000000; i++) { getName.invoke("person", null); } long endTime = System.currentTimeMillis(); System.out.println("反射方式执行10亿次;" + (endTime - startTime) + "ms"); } //关闭检测后,通过反射的方式调用 public static void text3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { person user = new person(); Class c = user.getClass(); Method getName = c.getDeclaredMethod("getName", null); getName.setAccessible(true); long startTime = System.currentTimeMillis(); for (int i = 0; i < 1000000000; i++) { getName.invoke("person", null); } long endTime = System.currentTimeMillis(); System.out.println("关闭检测后,执行10亿次;" + (endTime - startTime) + "ms"); } public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { text1(); text2(); text3(); } }
输出:
普通方式执行10亿次;4ms 反射方式执行10亿次;6576ms 关闭检测后,执行10亿次;5577ms