Can you invoke a method via reflection on behalf o

2019-08-05 05:04发布

问题:

I have a client.class that uses Util.class to invoke a method on target.class. The invocation is forced by calling the setAccessible(true) to the method of target.class.

Question: Is there a way to have this Util.class determine if the client.class has access to this particular method of target.class?

I want to skip having to use the method setAccessible(true). client.class has access to the method I am invoking in target.class, but Util.class does not have access because the method is protected or default.

回答1:

You might be able to establish whether the client class had access to the method by examining the packages, inheritance chain, and accessibility of the method. Take a look at the MethodModifierSpy class in the Java tutorials.

But even if the client class had access, your code in Util would still need to call setAccessible(true) when Util does not have access, since the reflection code is part of Util, not the client class.