更新时间:2023-02-15 16:11:36
匿名内部类有类型但没有名称。
Anonymous inner classes have a type but no name.
您可以访问未由指定超类型定义的字段。但是,一旦分配给命名类型变量,接口就会丢失。
You can access fields not defined by the named supertype. However once assigned to a named type variable, the interface is lost.
显然,您可以从内部类本身访问字段。添加代码的一种方法是通过实例初始化器:
Obviously, you can access the fields from within the inner class itself. One way of adding code is through an instance initialiser:
final AtomicInteger y = new AtomicInteger();
new Runnable() {
int x;
{
x = 5;
doRun(this);
y.set(x);
}
public void run() {
... blah ...
}
};
匿名内部类表达式返回的值具有匿名类型,因此您有一次机会使用它在类本身之外:
The value returned by the anonymous inner class expression has the anonymous type, so you have one chance to use it outside of the class itself:
final int y = new Runnable() {
int x;
{
x = 5;
doRun(this);
}
public void run() {
... blah ...
}
}.x;
您还可以通过类似于以下方式声明的方法传递它:
You can also pass it through a method declared similar to:
<T extends Runnable> T doRun(T runnable);