在匿名类中定义自定义函数/属性

Sim*_*Guy 1 java anonymous-types

我想在匿名类中定义我的属性和函数如下

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

         public String getMyProperty() { return someProperty }
});
Run Code Online (Sandbox Code Playgroud)

但是这些电话不起作用

aClass.someProperty // not accessible
aClass.getMyProperty() // not accessible
Run Code Online (Sandbox Code Playgroud)

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

rzw*_*oot 5

它们可以很好地访问:

new ExistingExtendable() {
    public void foo() {}
}.foo();
Run Code Online (Sandbox Code Playgroud)

效果很好。

但是如果你写:

ExistingExtendable x = new ExistingExtendable() {
    public void foo() {}
};
x.foo();
Run Code Online (Sandbox Code Playgroud)

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

Object o = new String();
o.toLowerCase(); // nope
Run Code Online (Sandbox Code Playgroud)

问题是您的匿名类没有名称,因此您无法表示其类型。我们可以通过替换Object o为来修复字符串示例String o,但没有String等效项。

然而,这就是匿名内部类的意义所在。

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

您可以创建方法本地内部类,现在您有了名称:

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!";
}
Run Code Online (Sandbox Code Playgroud)

匿名内部类与此方法本地类事物相同,只是它避免命名类型。在这种情况下,您需要该名称,因此,您不能使用匿名内部类构造。