不确定我是否在问一个合理的问题。我知道每个内部类都保持对封闭类对象的引用。在给定匿名内部类作为函数参数?
的情况下,我可以引用封闭类之外的封闭类对象吗?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!");
}
});
}
}
答案 0 :(得分:8)
获取t
封闭课程t.getClass().getEnclosingClass()
。请注意,如果没有封闭类,则会返回null
。
获取封闭类的正确实例并不容易,因为这将依赖于某些
未记录的实现细节(即this$0
变量)。以下是一些更多信息:In Java, how do I access the outer class when I'm not in the inner class?
编辑:我想再次强调this$0
方法没有记录,可能依赖于编译器。因此,请不要在生产或关键代码中依赖它。
答案 1 :(得分:0)
您可以执行此操作以查看t
是B
的内部类:
public static void foo(Thread t) {
System.out.println(t.getClass().getName().contains("B$"));
// OR
System.out.println(t.getClass().getEnclosingClass().equals(B.class));
}