java - 有没有办法访问另一个匿名类中的匿名类?

标签 java anonymous-class

interface A {
    void show();
}

public class Static {
    public static void main(String args[]) {
        A a = new A(){
            public void show(){
                System.out.println("In anonymous Class");
                A b =new A(){
                    public void show(){
                        System.out.println("In nested Anonymous Class");
                    }
                };
            }
        };
        //a.show();
    }
}

如果我想打印“In nested Anonymous Class”,我应该使用什么来代替 a.show()?

//稍后编辑

谢谢大家,但不幸的是,我打错了代码……我不是说方法内部的匿名类……而是在类本身内部。抱歉弄错了。这是更正后的代码

interface A {
    void show();
}

public class Static {
    public static void main(String args[]) {
        A a = new A() {
            public void show() {
                System.out.println("In anonymous Class");
            };

            A b = new A() {
                public void show() {
                    System.out.println("In nested Anonymous Class");
                }
            };
        };
        a.show();
    }
}

最佳答案

通常情况下,这是不可能的,因为 A 是一个接口(interface),而接口(interface)没有字段。但是,可以使用反射访问该字段。虽然有点 hack,但我不建议在“现实世界”中使用它!

interface A {
    void show();
}

public class Static {
    public static void main(String args[]) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {
        A a = new A() {
            public void show() {
                System.out.println("In anonymous Class");
            };

            public A b = new A() {
                public void show() {
                    System.out.println("In nested Anonymous Class");
                }
            };

        };
        // Get the anonymous Class object
        Class<? extends A> anonymousClass = a.getClass();
        // Get field "b"
        Field fieldB = anonymousClass.getField("b");
        // Get the value of b in instance a and cast it to A
        A b = (A) fieldB.get(a);
        // Show!
        b.show();
    }
}

注意:更好的方法可能是简单地在您的接口(interface)上为变量 b 声明一个 getter。

关于java - 有没有办法访问另一个匿名类中的匿名类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25823293/

相关文章:

java - 记录改造到 Logback 记录器

java - 在单独的线程中运行逻辑仍然锁定 UI - Java

java - 从内部匿名类调用外部类的函数(与外部相同的类)

java - 如何用Java中的匿名类替换监听器?

java - 如何为多个 JMenuItem 创建 ActionListener?

php - 在 "anonymous"对象中使用 $this

java - Android ImageView 按路径显示图片

java - 是否可以在 Spring Repository @Query 注释中动态设置模式?

java - 如何使用 pageFilter 避免扫描对象中的某些行?

java - Spring调度程序: start at 12:25PM and run every 15 minutes after that