在匿名 class 中定义自定义 function/property

Defining custom function/property inside anonymous class

我想将我的 属性 和匿名函数 class 定义为

ExistingExtendableJavaClass aClass = new ExistingExtendableJavaClass() {
         public String someProperty;

         public String getMyProperty() { return someProperty }
});

但是这些调用不起作用

aClass.someProperty // not accessible
aClass.getMyProperty() // not accessible

我知道,因为 ExistingExtendableJavaClass 没有这些,但是我的匿名用户有这些。我怎样才能做到这一点?

它们可以很好地访问:

new ExistingExtendable() {
    public void foo() {}
}.foo();

效果很好。

但是如果你写:

ExistingExtendable x = new ExistingExtendable() {
    public void foo() {}
};
x.foo();

那是行不通的。出于同样的原因,这不起作用:

Object o = new String();
o.toLowerCase(); // nope

问题是你的匿名 class 没有名字,因此你不能表示它的类型。我们可以通过将 Object o 替换为 String o 来修复字符串示例,但是没有 String 等价物。

不过,这就是匿名内心的点class.

如果您希望这些是可表示的,那么您不需要匿名内部 class。问:“我想要一个匿名内部 class,但我希望我在其中声明的新成员可以访问”就像问:“我想要一个圆圈,但是.. 有角”。

您可以使方法局部内部 classes,现在您有名称:

public void example(String x) {
    class IAmAMethodLocalClass extends ExistingExtendableJavaClass {
        String someProperty; // making them public is quite useless.

        String foo() {
            System.out.println(x); // you can access x here.
        }
    }

    IAmAMethodLocalClass hello = new IAmAMethodLocalClass();
    hello.someProperty = "It works!";
}

an anonymous inner class 与本地方法 class 相同,只是它避免命名类型。在这种情况下,你需要那个名字,因此,你不能使用匿名内部class结构。