访问内部匿名类成员 [英] Accessing inner anonymous class members
问题描述
除了使用反射来访问匿名内部类的成员之外还有什么方法吗?
Is there any way other than using reflection to access the members of a anonymous inner class?
推荐答案
匿名内部类有类型但没有名称。
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);
这篇关于访问内部匿名类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!