java普通调用方法以及通过反射调用方法和关闭反射安全访问权限的耗时比较
代码如下:
**import com.item.zhang.User;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test8 {
public static void test1() {
User user = new User();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
user.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通调用耗时:" + (endTime - startTime) + "ms");
}
public static void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c = user.getClass();
Method method = c.getDeclaredMethod("getName");
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
method.invoke(user, null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射未关闭权限耗时:" + (endTime - startTime) + "ms");
}**
**public static void test3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c = user.getClass();
Method method = c.getDeclaredMethod("getName");
method.setAccessible(true);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
method.invoke(user, null);
}
long endTime = System.currentTimeMillis();
System.out.println("关闭权限耗时:" + (endTime - startTime) + "ms");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test1();
test2();
test3();
}
}**