是否可以通过.THIS 关键字指向匿名class?

Is it possible to point to anonymous class by .THIS keyword?

SSCCE:

public class Test {
    public Test() {
        new Anonymous1() {
            void validate() {
                new Anonymous2() {
                    int calculate() {
                        return Math.abs(Anonymous1.this.getValue()); // compilation error - Anonymous1 is not an enclosing class
                    }
                };
            }
        };
    }
}

abstract class Anonymous1 {
    abstract void validate();

    int getValue() {
        return 0;
    }
}

abstract class Anonymous2 {
    abstract int calculate();
}

我知道它看起来很复杂而且无法使用,但我只是想知道是否可以使用 .this 指针从 Anonymous2 指向 Anonymous1 class,或者以任何其他方式。

您需要在 class 中完成。

public Test() {
    new Anonymous1() {
        void validate() {
            final Object this1 = this;
            new Anonymous2() {
                int calculate() {
                    return Math.abs(this1.getValue()); 
                }
            }
        }
    }
}

或者更好的是,首先提取你需要的东西并有效地使用最终添加在 Java 8.

public Test() {
    new Anonymous1() {
        void validate() {
            int value = getValue();
            new Anonymous2() {
                int calculate() {
                    return Math.abs(value); 
                }
            }
        }
    }
}

如果 Anonymous1Anonymous2 是您可以在 Java 8.

中使用 lambda 的接口
public Test() {
   Anonymous1 a = () -> {
      int v = getValue();
      Anonymous2 = a2 = () -> Math.abs(v);
   };

}