实际开发中,setAccessible具体的用处主要有两处:
作用于方法上,method.setAccessible(true);
public static void test02() throws Exception{ User u = new User(); Class clazz = u.getClass(); Method m = clazz.getDeclaredMethod("getUname", null); m.setAccessible(true); m.invoke(u, null); }
作用于属性上,field.setAccessible(true);
if (field.isAnnotationPresent(TestIdSign.class)){ try { field.setAccessible(true); field.set(object,testId); } catch (IllegalAccessException e) { throw new RuntimeException("set testID illegalAccessException",e); } }
将此对象的 accessible 标志设置为指示的布尔值。值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。值为 false 则指示反射的对象应该实施 Java 语言访问检查;实际上setAccessible是启用和禁用访问安全检查的开关,并不是为true就能访问为false就不能访问 ;
由于JDK的安全检查耗时较多.所以通过setAccessible(true)的方式关闭安全检查就可以达到提升反射速度的目的
如下例子:参考(http://huoyanyanyi10.iteye.com/blog/)
package com.chenshuyi.test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Method m = A.class.getDeclaredMethod("getName", new Class[] {}); System.out.println(m.isAccessible()); // getName是public的,猜猜输出是true还是false A a = new A(); a.setName("Mr Lee"); long start = System.currentTimeMillis(); for (int i = 0; i < ; i++) { m.invoke(a, new Object[] {}); } System.out.println("Simple :" + (System.currentTimeMillis() - start)); m.setAccessible(true); // 注意此处不同 long start1 = System.currentTimeMillis(); for (int i = 0; i < ; i++) { m.invoke(a, new Object[] {}); } System.out.println("setAccessible(true) :" + (System.currentTimeMillis() - start1)); } } class A { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
使用了method.setAccessible(true)后 性能有了20倍的提升;
Accessable属性是继承自AccessibleObject 类. 功能是启用或禁用安全检查 ;
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/223290.html原文链接:https://javaforall.net
