get Enclosing Instance from Object - Android java.lang.reflect

Android examples for java.lang.reflect:Nested Class

Description

get Enclosing Instance from Object

Demo Code


//package com.java2s;

import java.lang.reflect.Field;

public class Main {
    public static Object getEnclosingInstance(Object innerInstance) {
        int depth = -1;
        Object result = innerInstance;

        try {/*from   ww w. ja  va 2 s.c om*/
            Class<?> enclosing = innerInstance.getClass()
                    .getEnclosingClass();
            while (enclosing != null) {
                ++depth;
                Field field = getField(result.getClass(), "this$" + depth);
                field.setAccessible(true);
                result = field.get(result);
                enclosing = enclosing.getEnclosingClass();
            }
        } catch (Throwable ex) {
            return null;
        }

        return result;
    }

    public static Field getField(Class<?> clazz, String fieldName) {
        Class<?> cl = clazz;
        while (cl != null) {
            try {
                return cl.getDeclaredField(fieldName);
            } catch (NoSuchFieldException ex) {
                cl = cl.getSuperclass();
            }
        }

        return null;
    }
}

Related Tutorials