Getting hold of the outer class object from the inner class object

前端 未结 8 1251
孤独总比滥情好
孤独总比滥情好 2020-11-22 02:26

I have the following code. I want to get hold of the outer class object using which I created the inner class object inner. How can I do it?

pub         


        
8条回答
  •  无人及你
    2020-11-22 03:03

    You could (but you shouldn't) use reflection for the job:

    import java.lang.reflect.Field;
    
    public class Outer {
        public class Inner {
        }
    
        public static void main(String[] args) throws Exception {
    
            // Create the inner instance
            Inner inner = new Outer().new Inner();
    
            // Get the implicit reference from the inner to the outer instance
            // ... make it accessible, as it has default visibility
            Field field = Inner.class.getDeclaredField("this$0");
            field.setAccessible(true);
    
            // Dereference and cast it
            Outer outer = (Outer) field.get(inner);
            System.out.println(outer);
        }
    }
    

    Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)

提交回复
热议问题