笔记:setAccessible方法启用/禁用权限控制检查
class A {
private int i;
public int getI(){
return i;
}
private void setI(int i) {
this.i = i;
}
}
Class<?> clazz= Class.forName("hadoopclient.A");
Field iField =clazz.getDeclaredField("i");
System.out.println("i: "+iField);
Method getI = clazz.getMethod("getI", newClass[]{});
System.out.println("getI:\t"+getI);
Method setI = clazz.getDeclaredMethod("setI", newClass[]{int.class});
System.out.println("setI:\t"+setI);
Object newInstance = clazz.newInstance();
Object returnValue = getI.invoke(newInstance,newClass<?>[]{});
System.out.println("init:\t"+returnValue);
setI.setAccessible(true); //若无此句将抛异常
setI.invoke(newInstance, newObject[]{100});
returnValue = getI.invoke(newInstance, newClass<?>[]{});
System.out.println("invokesetI(100):\t"+returnValue);
}
}
注意:
setAccessible(true)并不是将方法的访问权限改成了public,而是取消java的权限控制检查。所以即使是public方法,其accessible属相默认也是false
JDK 文档:
setAccessible
public void setAccessible(boolean flag) throws SecurityException
- Setthe accessible flag forthis object to the indicated boolean value. A valueof true indicates thatthe reflected object should suppress Java language access checkingwhen it is used. A valueof false indicates thatthe reflected object should enforce Java language access checks.
First, if there is a security manager,its
checkPermission
methodis called withaReflectPermission("suppressAccessChecks")
permission.A
SecurityException
israisedifflag
istrue
butaccessibility of this object may not be changed (for example, ifthis element object is aConstructor
objectfor the classClass
).A
SecurityException
israised if this object is aConstructor
objectfor the classjava.lang.Class
,andflag
istrue. - Parameters:
flag
- the new value forthe accessible flag- Throws:
SecurityException
-if the request is denied.- See Also:
SecurityManager.checkPermission(java.security.Permission)
,RuntimePermission
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步