我可以使用一些语法访问匿名内部类中的新方法吗?

编程入门 行业动态 更新时间:2024-10-07 00:24:41
本文介绍了我可以使用一些语法访问匿名内部类中的新方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有任何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; }

更多推荐

我可以使用一些语法访问匿名内部类中的新方法吗?

本文发布于:2023-11-02 06:22:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551608.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   新方法   语法   类中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!