Java reflection: access private method inside inner class

南笙酒味 提交于 2019-12-23 12:16:18

问题


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;
        }
    }
}

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.

My current code:

Outer outerObject = new Outer();
Constructor<?> constructor = innerNodeClass.getDeclaredConstructor(Outer.class);
constructor.setAccessible(true);
Object innerObject = constructor.newInstance(outerObject);
innerObject.someMethod(5)

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.


回答1:


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);


来源:https://stackoverflow.com/questions/52529608/java-reflection-access-private-method-inside-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!