Get a private class object from an anonymous inner class as a function parameter

Not sure if I am asking the right question. I know that every inner class stores a reference to a class object. Can I refer to an object of the closing class outside the class that the class includes if the anonymous inner class is a parameter of the function?

class A{ public static void foo(Thread t) { //here, how to get the reference of the enclosing class object of "t", //ie 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!"); } }); } } 
+4
source share
2 answers

To get the t class to include, try t.getClass().getEnclosingClass() . Note that this would return null if there was no closing class.

Getting the right instance of the enclosing class is not easy, as it will rely on some details of an undocumented implementation (namely, the variable this$0 ). Here's another piece of information: In Java, how do I access an outer class when I'm not in an inner class?

Edit: I would like to emphasize once again that this$0 approach is undocumented and may be compiler dependent. Therefore, please do not rely on what is in production or in critical code.

+7
source

You can do this to see if t 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
source

Source: https://habr.com/ru/post/1393256/


All Articles