Java:反射调用实现公共接口的非公共类中的方法
我尝试使用反射来调用名称和参数在运行时已知的方法,但失败并出现 IllegalAccessException
。
这是一个对象,该对象是实现公共接口的非公共类的实例,我在试图记住调用此类方法的正确方法时感到脑抽筋。
public interface Foo
{
public int getFooValue();
}
class FooImpl implements Foo
{
@Override public int getFooValue() { return 42; }
}
Object foo = new FooImpl();
给定 foo 对象,我如何反射性地调用 foo.getFooValue() ?
如果我查看 foo.getClass().getMethods() 的结果,这应该可以工作,但我认为它会导致 IllegalAccessException
这是我必须调用的情况吗getDeclaredMethods()
?或者我是否必须遍历公共接口/超类并在那里调用 getDeclaredMethods ?
I'm trying to use reflection to invoke a method whose name and arguments are known at runtime, and I'm failing with an IllegalAccessException
.
This is on an object that is an instance of a nonpublic class which implements a public interface, and I've got a brain cramp trying to remember the right way to invoke such a method.
public interface Foo
{
public int getFooValue();
}
class FooImpl implements Foo
{
@Override public int getFooValue() { return 42; }
}
Object foo = new FooImpl();
Given the foo
object, how would I call foo.getFooValue() reflectively?
If I look through the results of foo.getClass().getMethods()
, this should work but I think it causes the IllegalAccessException
Is this a case where I have to call getDeclaredMethods()
? Or do I have to walk through the public interfaces/superclasses and call getDeclaredMethods
there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这有效:
This works:
我认为你应该调用 getDeclaredMethods()。
这里是一个示例:
顺便说一句,有一篇文章引用了 '<一个href="https://stackoverflow.com/questions/5951197/accessing-private-inner-class-in-the-same-package/5952096#5952096">私有类反射':
I think that you should call the getDeclaredMethods().
Here's an example:
By the way, a post refering to 'private classes reflection':