有什么方法可以调用私有方法? [英] Any way to Invoke a private method?
问题描述
我有一个类,它使用 XML 和反射将 Object
返回给另一个类.
I have a class that uses XML and reflection to return Object
s to another class.
通常这些对象是外部对象的子字段,但有时我想即时生成它.我试过这样的事情,但无济于事.我相信这是因为 Java 不允许您访问 private
反射方法.
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.
长话短说,我只是想知道是否有办法通过反射访问 private
方法.
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
或 Subject
).
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屋!