public static void test01(){ User user = new User(); 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 test02(){ User user = new User(); User user= user.getclass(); Method getName = user.getDeclaredMethod("getName",null); long startTime = System.currentTimeMillis(); for (int i = 0;i<1000000000;i++){ getName.invoke("user",null); } long endTime = System.currentTimeMillis(); System.out.println("反射方式执行10亿次"+(endTime-startTime)+"ms"); } public static void test03(){ User user = new User(); long startTime = System.currentTimeMillis(); get.Name.setAccessible(true); for (int i = 0;i<1000000000;i++){ user.getName(); } long endTime = System.currentTimeMillis(); System.out.println("关闭监测执行10亿次"+(endTime-startTime)+"ms"); }
然后写一个main方法,去调用三个方法
反射方法的时间最长,然后关闭监测执行的最后普通方式执行的最快