从匿名内部类中获取封闭类对象作为函数参数 [英] get the enclosing class object from anonymous inner class as function parameter
问题描述
不确定我是否在问一个合理的问题。我知道每个内部类都保持对封闭类对象的引用。给定匿名内部类作为函数参数,我可以引用封闭类之外的封闭类对象吗?
Not sure if I am asking a sound question. I know every inner class keeps a reference to the enclosing class object. So can I reference the enclosing class object outside that enclosing class given the anonymous inner class as function parameter?
class A{
public static void foo(Thread t) {
//here, how to get the reference of the enclosing class object of "t",
//i.e. the object of class B. I know, somebody might have put in a
//non-inner class Thread. But how can I check if "t" is really from an
//anonymous inner class of class B and then do something here?
}
}
class B{
public void bar() {
A.foo(
new Thread() {
public void run() {
System.out.println("inside bar!");
}
});
}
}
推荐答案
获取 t
的封闭类,尝试 t.getClass()。getEnclosingClass()
。请注意,如果没有封闭类,这将返回 null
。
For getting the enclosing class of t
try t.getClass().getEnclosingClass()
. Note that this would return null
if there was no enclosing class.
获取封闭类的正确实例是不那么容易,因为这将依赖于一些
未记录的实现细节(即这个$ 0
变量)。以下是一些更多信息:在Java中,当我不在内部类时,如何访问外部类?
Getting the correct instance of the enclosing class is not that easy, since this would rely on some
undocumented implementation details (namely the this$0
variable). Here's some more information: In Java, how do I access the outer class when I'm not in the inner class?
编辑:我想再次强调这个$ 0
方法是未记录的,可能与编译器有关。因此,请不要依赖于生产或关键代码。
Edit: I'd like to reemphasize that the this$0
approach is undocumented and might be compiler dependent. Thus please don't rely on that in production or critical code.
这篇关于从匿名内部类中获取封闭类对象作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!