反射机制对程序的运行在性能上有一定的影响,速度慢
3.1如何提高反射的性能
1)通过setAccessible提高性能
a) setAccessible启用和禁用访问安全检查的开关,值为
true
则指示反射的对象在使用时应该取消Java语言访
问检查,值为false则指示反射的对象应访实施Java
语言访问检查,并不是为true就能访问为false就不能
访问
b)禁止安全检查,可以提高反射的运行速度

 

 

package ReflectEntity;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;public class Test {
	public static void test01(){
		//User u=new User();
		Object obj=new Object();
		long startTime=System.currentTimeMillis();
		for(int i=0;i<1000000000L;i++){
			obj.hashCode();
		}
		long endTime=System.currentTimeMillis();
		System.out.println("调用普通方法,执行10亿次:"+(endTime-startTime)+"ms");
	}
	public static void test02() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		Object obj=new Object();
		Class c=obj.getClass();
		//获取指定的方法
		Method m=c.getDeclaredMethod("hashCode", null);
		long startTime=System.currentTimeMillis();
		for(int i=0;i<1000000000L;i++){
			//执行这个方法
			m.invoke(obj, null);
		}
		long endTime=System.currentTimeMillis();
		System.out.println("通过反射动态方法调用,执行10亿次:"+(endTime-startTime)+"ms");
	}
	public static void test03() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		Object obj=new Object();
		Class c=obj.getClass();
		//获取指定的方法
		Method m=c.getDeclaredMethod("hashCode", null);

		m.setAccessible(true);//不执行安全检查

		long startTime=System.currentTimeMillis();
		for(int i=0;i<1000000000L;i++){
			//执行这个方法
			m.invoke(obj, null);
		}
		long endTime=System.currentTimeMillis();
		System.out.println("通过反射动态方法调用,不启用安全检查,执行10亿次:"+(endTime-startTime)+"ms");
	}
	public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		test01();
		test02();
		test03();
	}

}

 

 

据说,通常反射比普通方法慢30倍,关闭安全检查能将速度提升4倍