普通方式调用
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() throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
Class c1 = Class.forName("com.sty.reflection.User");
User user = (User) c1.newInstance();
Method getName = c1.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() throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
Class c1 = Class.forName("com.sty.reflection.User");
User user = (User) c1.newInstance();
Method getName = c1.getDeclaredMethod("getName", null);
getName.setAccessible(true); // 关闭检测
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 main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
test01();
test02();
test03();
}
执行结果
普通方式执行10以次:3ms
反射方式执行10以次:1458ms
反射方式 关闭检测 执行10以次:1147ms
结论
如果一定要通过反射的方式创建对象,最好将 getName.setAccessible(true); // 关闭检测 这个设置上
知识来源
标签:反射,getName,System,long,创建对象,User,startTime,对比,user From: https://www.cnblogs.com/styCy/p/17158932.html