简体   繁体   English

您可以代表其他类通过反射调用方法吗

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

I have a client.class that uses Util.class to invoke a method on target.class. 我有一个使用Util.class来调用target.class上的方法的client.class。 The invocation is forced by calling the setAccessible(true) to the method of target.class. 通过调用target.class方法的setAccessible(true)强制调用。

Question: Is there a way to have this Util.class determine if the client.class has access to this particular method of target.class? 问题:有没有一种方法可以让此Util.class确定client.class是否有权访问target.class的此特定方法?

I want to skip having to use the method setAccessible(true). 我想跳过不必使用方法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. client.class可以访问我在target.class中调用的方法,但是Util.class不能访问,因为该方法是受保护的或默认的。

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 . 看一下Java教程中的MethodModifierSpy

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. 但是,即使客户机类具有访问权限,但在Util无权访问时, Util中的代码仍需要调用setAccessible(true) ,因为反射代码是Util一部分,而不是客户机类的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM