Can you invoke a method via reflection on behalf of another class

此生再无相见时 提交于 2019-12-24 10:06:34

问题


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.



来源:https://stackoverflow.com/questions/22468373/can-you-invoke-a-method-via-reflection-on-behalf-of-another-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!