get the enclosing class object from anonymous inner class as function parameter

前端 未结 2 761
猫巷女王i
猫巷女王i 2021-01-06 03:15

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 tha

相关标签:
2条回答
  • 2021-01-06 03:52

    For getting the enclosing class of t try t.getClass().getEnclosingClass(). Note that this would return null if there was no enclosing class.

    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?

    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.

    0 讨论(0)
  • 2021-01-06 03:52

    You can do this to see if t is an inner class of 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));
    }
    
    0 讨论(0)
提交回复
热议问题