是否有任何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; }更多推荐
我可以使用一些语法访问匿名内部类中的新方法吗?
发布评论