为什么在Java中的匿名类中添加公共字段不起作用? [英] Why does adding a public field to an anonymous class in Java not work?
问题描述
我有一个如下定义的示例类:
I have an example class defined like below:
public class FooBar {
void method1(Foo foo){ // Should be overwritten
...
}
}
稍后,当我尝试这个时:
Later, when I try this:
FooBar fooBar = new FooBar(){
public String name = null;
@Override
void method1(Foo foo){
...
}
};
fooBar.name = "Test";
我收到一条错误消息,指出名称字段不存在。为什么?
I get an error saying that the name field does not exist. Why?
推荐答案
因为变量的类型 fooBar
是 FooBar
(所述变量中对象的运行时类型是实现 FooBar
的匿名类,它也是 FooBar
的子类型 ... ...
Because the type of the variable "fooBar"
is FooBar
(the run-time type of the object in said variable is that of the anonymous class implementing FooBar
which is also a subtype of FooBar
)...
...类型 FooBar
没有所述成员。因此,编译错误。 (请记住,变量fooBar
可以包含符合 FooBar
的任何对象,即使是那些没有 name
,因此编译器会拒绝非类型安全的代码。)
...and the type FooBar
does not have said member. Hence, a compile error. (Remember, the variable "fooBar"
can contain any object conforming to FooBar
, even those without name
, and thus the compiler rejects the code which is not type-safe.)
编辑:有关一个解决方案,请参阅不可信的答案,使用本地班级声明创建一个新的命名类型(替换帖子中的匿名类型)。
For one solution, see irreputable's answer which uses a Local Class Declaration to create a new named type (to replace the anonymous type in the post).
Java 不支持支持这种方式(主要是:Java不支持有用的类型推断),虽然以下工作正常,即使不是很有用:
Java does not support a way to do this (mainly: Java does not support useful type inference), although the following does work, even if not very useful:
(new foobar(){
public String name = null;
@Override
void method1(Foo foo){
...
}
}).name = "fred";
快乐编码。
Scala和C#都支持所需的类型推断,因此支持局部变量的匿名类型特化。 (尽管C#不支持匿名扩展现有类型)。但是,Java没有。
Both Scala and C# support the required type inference, and thus anonymous type specializations, of local variables. (Although C# does not support extending existing types anonymously). Java, however, does not.
这篇关于为什么在Java中的匿名类中添加公共字段不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!