繁体   English   中英

在内部类内部调用私有类内部的私有方法

[英]Calling private method inside private class inside Inner class

需要调用类Inner.Private的私有方法foo() ,其中Private是来自主类的 main 方法的内部私有类。 代码是这样的:

public class MainClass {
    public static void main(String[] args) throws Exception {
        // Need to invoke foo() from here
        } 

    static class Inner {
        private class Private {
            private String foo() {
                return "someString";
            }
        }
    }
}

我试图使用 Java 反射来获得它,但我面临着这种方法的问题。

我调用foo()尝试是:

        Inner innerClassObject = new Inner();
        Method method = Inner.Private.class.getDeclaredMethod("foo");
        method.setAccessible(true);
        method.invoke(innerClassObject);

但这给出了一个 NoSuchMethodException:

Exception in thread "main" java.lang.NoSuchMethodException: 
default.MainClass$Inner$Private.foo()
    at java.lang.Class.getDeclaredMethod(Unknown Source) 

我被困在这一点上,这可以通过 Java 反射或任何其他方式实现吗?

嗯...为什么不简单地new Inner().new Private().foo()

你为什么做这个

Inner.Private.class

代替

innerClassObject.getClass()

例如:

public class Test {


private int foo(){
    System.out.println("Test"); 
    return 1;
}
public static void main(String [] args) throws InterruptedException, 
NoSuchMethodException, IllegalAccessException, IllegalArgumentException, 
InvocationTargetException
{
  Test innerClassObject = new Test();
    Method method = 
    innerClassObject.getClass().getDeclaredMethod("foo",null);
    method.setAccessible(true);
    method.invoke(innerClassObject);
}


}

为什么只是为了调用所描述的方法而浪费实例化? 随着类的发展,您将不可避免地希望保存各种实例以备后用。

public class MainClass {
    public static void main(String[] args) throws Exception {
        // Need to invoke foo() from here
        Inner inner = new Inner();
        Inner.Private pvt = inner.new Private();
        System.out.println(pvt.foo());
    }

    static class Inner {
        private class Private {
            private String foo() {
                return "someString";
            }
        }
    }
}

印刷

someString

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM