Can I access new methods in anonymous inner class with some syntax?

前端 未结 7 2203
深忆病人
深忆病人 2020-12-01 14:48

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 sy

7条回答
  •  北海茫月
    2020-12-01 14:49

    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 identity(T value) {
        return value;
    }
    

提交回复
热议问题