有什么方法可以调用私有方法吗? [英] Any way to Invoke a private method?

查看:113
本文介绍了有什么方法可以调用私有方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用XML和反射的类将 Object 返回给另一个类。

I have a class that uses XML and reflection to return Objects to another class.

通常这些对象是外部对象的子字段,但有时它是我想要动态生成的东西。我尝试过类似的东西,但无济于事。我相信这是因为Java不允许您访问私有方法进行反思。

Normally these objects are sub fields of an external object, but occasionally it's something I want to generate on the fly. I've tried something like this but to no avail. I believe that's because Java won't allow you to access private methods for reflection.

Element node = outerNode.item(0);
String methodName = node.getAttribute("method");
String objectName = node.getAttribute("object");

if ("SomeObject".equals(objectName))
    object = someObject;
else
    object = this;

method = object.getClass().getMethod(methodName, (Class[]) null);

如果提供的方法是 private ,使用 NoSuchMethodException 失败。我可以通过使方法 public 来解决它,或者让另一个类从中派生出来。

If the method provided is private, it fails with a NoSuchMethodException. I could solve it by making the method public, or making another class to derive it from.

长话短说,我只是想知道是否有办法通过反射访问私人方法。

Long story short, I was just wondering if there was a way to access a private method via reflection.

推荐答案

您可以使用反射调用私有方法。修改已发布代码的最后一位:

You can invoke private method with reflection. Modifying the last bit of the posted code:

Method method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
Object r = method.invoke(object);

有几点需要注意。首先, getDeclaredMethod 将只查找在当前 Class 中声明的方法,而不是从超类型继承。因此,如有必要,遍历具体的类层次结构。其次, SecurityManager 可以阻止使用 setAccessible 方法。因此,它可能需要以 PrivilegedAction 运行(使用 AccessController 主题)。

There are a couple of caveats. First, getDeclaredMethod will only find method declared in the current Class, not inherited from supertypes. So, traverse up the concrete class hierarchy if necessary. Second, a SecurityManager can prevent use of the setAccessible method. So, it may need to run as a PrivilegedAction (using AccessController or Subject).

这篇关于有什么方法可以调用私有方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆