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

前端 未结 8 1264
孤独总比滥情好
孤独总比滥情好 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 02:58

    /**
     * Not applicable to Static Inner Class (nested class)
     */
    public static Object getDeclaringTopLevelClassObject(Object object) {
        if (object == null) {
            return null;
        }
        Class cls = object.getClass();
        if (cls == null) {
            return object;
        }
        Class outerCls = cls.getEnclosingClass();
        if (outerCls == null) {
            // this is top-level class
            return object;
        }
        // get outer class object
        Object outerObj = null;
        try {
            Field[] fields = cls.getDeclaredFields();
            for (Field field : fields) {
                if (field != null && field.getType() == outerCls
                        && field.getName() != null && field.getName().startsWith("this$")) {
                    field.setAccessible(true);
                    outerObj = field.get(object);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getDeclaringTopLevelClassObject(outerObj);
    }
    

    Of course, the name of the implicit reference is unreliable, so you shouldn't use reflection for the job.

提交回复
热议问题