java 反射(二)之提高反射的方法 setAccessible(true)

setAccessible(true/false):表示启用和禁用安全检查的开关。

当值为true时,指反射对象在使用时应该取消java语言访问检查,值为false则只是反射的对象应该试试java语言访问检查。当    值        设置为true时,不接受检查,可以提高反射的运行速度。

package com.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {

	public static void main(String[] args) throws NoSuchFieldException, SecurityException {
		
		
		User u=new User();
		Class clazz=u.getClass();
		
		//第一种,直接调用
		long start1=System.currentTimeMillis();
		for(long i=0;i<100000000;i++) {
			u.setName("张三");
		}
		long end1=System.currentTimeMillis();
		System.out.println("直接调用方法的时间:"+(end1-start1)+"ms");
		
		//第二种
		
		long start2=System.currentTimeMillis();
			try {
				for(long i=0;i<100000000;i++) {
					Method method=clazz.getDeclaredMethod("setName", String.class);	
					method.invoke(u, "张三");
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			long end2=System.currentTimeMillis();	
			
			System.out.println("不加setAccessible(true)调用方法的时间:"+(end2-start2)+"ms");
		
    
		
		
		//第三种
			long start3=System.currentTimeMillis();
			try {
				for(long i=0;i<100000000;i++) {
					Method method=clazz.getDeclaredMethod("setName", String.class);	
					method.setAccessible(true);
					method.invoke(u, "张三");
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			long end3=System.currentTimeMillis();	
			System.out.println("加了setAccessible(true)调用方法,跳过安全检查后执行的的时间:"+(end3-start3)+"ms");
	}

}

 测试结果:

直接调用方法的时间:95ms
不加setAccessible(true)调用方法的时间:20439ms
加了setAccessible(true)调用方法,跳过安全检查后执行的的时间:18706ms

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值