Java AccessibleObject类的setAccessible方法具有布尔参数的原因是什么?
我在思考方面很新,我有一个疑问:Java AccessibleObject类的setAccessible方法具有布尔参数的原因是什么?,java,reflection,signature,Java,Reflection,Signature,我在思考方面很新,我有一个疑问: public void setAccessible(boolean flag) throws SecurityException public void setAccessible() throws SecurityException 此方法有一个boolen参数标志,指示任何字段或方法的新可访问性。 例如,如果我们试图从类外部访问类的private方法,那么我们使用getDeclaredMethod获取该方法,并将可访问性设置为true,这样就可以调用它,
public void setAccessible(boolean flag) throws SecurityException
public void setAccessible() throws SecurityException
此方法有一个boolen
参数标志,指示任何字段或方法的新可访问性。例如,如果我们试图从类外部访问类的
private
方法,那么我们使用getDeclaredMethod
获取该方法,并将可访问性设置为true
,这样就可以调用它,比如:method.setAccessible(true)代码>
现在在哪种情况下我们应该使用method.setAccessible(false)代码>,例如,当存在public
方法并且我们将可访问性设置为false时,可以使用它。但这有什么必要呢?我的理解清楚吗?
如果没有使用method.setAccessible(false)
,那么我们可以更改方法签名,如:
public void setAccessible(boolean flag) throws SecurityException
public void setAccessible() throws SecurityException
场景:您使用field.setAccessible(true)从一个私有字段中删除了保护,
读取该字段,并使用field.setAccessible(false)将该字段返回到原始状态。
可能您一生中都不会这样做setAccessible(false)
。这是因为setAccessible不会永久更改成员的可见性。当您访问类似method.setAccessible(true)
的对象时,即使原始源中的方法是私有的,您也可以对此方法
实例进行后续调用
例如,考虑这个:
A.java
*******
public class A
{
private void fun(){
....
}
}
B.java
***********
public class B{
public void someMeth(){
Class clz = A.class;
String funMethod = "fun";
Method method = clz.getDeclaredMethod(funMethod);
method.setAccessible(true);
method.invoke(); //You can do this, perfectly legal;
/** but you cannot do this(below), because fun method's visibilty has been
turned on public only for the method instance obtained above **/
new A().fun(); //wrong, compilation error
/**now you may want to re-switch the visibility to of fun() on method
instance to private so you can use the below line**/
method.setAccessible(false);
/** but doing so doesn't make much effect **/
}
}您不想让代码处于程序员不希望看到的反射状态。你…吗?您使用反射来解锁一段代码以供检查,您想在之后将其解锁吗?Downvoter您可以发表评论,以便我可以改进我的问题。您可以这样做,但没有任何效果,因为您不会通过再次将其设置为false来保护可访问性,因为任何客户机都可以随时获取字段实例并再次使用setAccessible(true)来使用该字段。此外,setAccessible不会永久性地改变字段的可访问性,也不会以非反射方式改变字段的可访问性,因此您可以保护它不受以非反射方式使用字段的客户端的影响。同意,但我们始终必须这样做。没有人会在这里传递false
值。那么,为什么还要费心多写一行代码呢?