反射与注解性能测试
1 package 反射与注解; 2 3 import 反射与注解.POJO.User; 4 5 import javax.jws.soap.SOAPBinding; 6 import java.lang.reflect.InvocationTargetException; 7 import java.lang.reflect.Method; 8 9 public class 反射性能测试 { 10 // 普通正常调用 11 public static void test01() { 12 long startTime = System.currentTimeMillis(); 13 User user = new User(); 14 for (int i = 0; i < 1000000000; i++) { 15 user.getName(); 16 } 17 long endTime = System.currentTimeMillis(); 18 19 System.out.println("普通调用方法使用时间为->" + (endTime - startTime) + "ms"); 20 } 21 22 // 反射调用 23 public static void test02() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, 24 InvocationTargetException { 25 long startTime = System.currentTimeMillis(); 26 Class<?> c1 = Class.forName("反射与注解.POJO.User"); 27 User user = (User) c1.newInstance(); 28 Method getName = c1.getDeclaredMethod("getName", null); 29 30 31 for (int i = 0; i < 1000000000; i++) { 32 getName.invoke(user, null); 33 } 34 long endTime = System.currentTimeMillis(); 35 36 System.out.println("普通调用方法使用时间为->" + (endTime - startTime) + "ms"); 37 } 38 39 // 反射后关闭安全检测调用 40 public static void test03() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, 41 InvocationTargetException { 42 long startTime = System.currentTimeMillis(); 43 Class<?> c1 = Class.forName("反射与注解.POJO.User"); 44 User user = (User) c1.newInstance(); 45 Method getName = c1.getDeclaredMethod("getName", null); 46 getName.setAccessible(true); 47 48 for (int i = 0; i < 1000000000; i++) { 49 getName.invoke(user, null); 50 } 51 long endTime = System.currentTimeMillis(); 52 53 System.out.println("普通调用方法使用时间为->" + (endTime - startTime) + "ms"); 54 } 55 56 public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { 57 test01(); 58 test02(); 59 test03(); 60 } 61 }
执行结果