问题描述
在使用反射API的公共类中的私有类中使用私有方法时,我遇到了问题。下面是一个简化的代码示例:
I'm having issues using a private method inside a private class inside a public class using the reflections api. Here's a simplified code example:
public class Outer {
private class Inner {
private Integer value;
private Inner() {
this(0);
}
private Inner(Integer y) {
value = y;
}
private Integer someMethod(Integer x) {
return x * x;
}
}
}
我也想成为能够实例化外部
类对象,然后从私有内部$ c调用
someMethod
$ c>类。我一直在尝试使用反射进行此操作,但是似乎无法超过1级。而且,内部类可能具有也可能没有大多数代码似乎都在使用的构造函数。上面的代码只是框架。
Again, I want to be able to instantiate an Outer
class object then call someMethod
from the private Inner
class. I've been trying to do this with reflections, but I can't seem to get past 1 level in. Also, the inner class may or may not have a constructor which most code seems to use. The above code is just the framework.
我当前的代码:
Outer outerObject = new Outer();
Constructor<?> constructor = innerNodeClass.getDeclaredConstructor(Outer.class);
constructor.setAccessible(true);
Object innerObject = constructor.newInstance(outerObject);
innerObject.someMethod(5)
我查找了各种进入内部类的方法或私有方法,但找不到不使用构造函数将外部对象转换为内部对象的方法。我只对在外部对象的元素上的内部类中使用private方法感兴趣。
I looked up various ways to get to an inner class or private method, but can't find a way to get an outer object to an inner object without using the constructor. I'm only interested in using the private method in the inner class on an element in the outer object.
推荐答案
一旦有了内部对象的实例,就可以使用反射来调用方法本身:
Once you have an instance of the inner object, you can use reflection to invoke the method itself:
Method someMethod = innerObject.getClass().getDeclaredMethod("someMethod", Integer.TYPE);
someMethod.setAccessible(true);
someMethod.invoke(innerObject, 5);
这篇关于Java反思:访问内部类内部的私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!