我可以使用某些语法访问匿名内部类中的新方法吗? [英] Can I access new methods in anonymous inner class with some syntax?

查看:26
本文介绍了我可以使用某些语法访问匿名内部类中的新方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何 Java 语法可以从外部类访问匿名内部类中定义的新方法?我知道可以有多种解决方法,但我想知道是否存在特殊语法?

Is there any Java syntax to access new methods defined within anonymous inner classes from outer class? I know there can be various workarounds, but I wonder if a special syntax exist?

例如

class Outer {

    ActionListener listener = new ActionListener() {

        @Override
        void actionPerformed(ActionEvent e) { 
             // do something
        }

        // method is public so can be accessible
        public void MyGloriousMethod() {
             // viva!
        }

    };

    public void Caller() {
         listener.MyGloriousMethod(); // does not work!
    }


}

我自己的解决方案

我只是将所有方法和成员移至外部类.

I just moved all methods and members up to outer class.

推荐答案

一旦匿名类实例被隐式转换为命名类型,它就无法转换回,因为匿名类型没有名称.您可以在类内通过this访问匿名内部类的其他成员,在紧接在表达式之后的表达式中,可以通过方法调用推断和返回类型.

Once the anonymous class instance has been implicitly cast into the named type it can't be cast back because there is no name for the anonymous type. You can access the additional members of the anonymous inner class through this within the class, in the expression immediate after the expression and the type can be inferred and returned through a method call.

Object obj = new Object() {
    void fn() {
        System.err.println("fn");
    }
    @Override public String toString() {
        fn();
        return "";
    } 
};
obj.toString();



new Object() {
    void fn() {
        System.err.println("fn");
    }
}.fn();


identity(new Object() {
    void fn() {
        System.err.println("fn");
    }
}).fn();
...
private static <T> T identity(T value) {
    return value;
}

这篇关于我可以使用某些语法访问匿名内部类中的新方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆