lundi 15 août 2016

Reflection get field of singleton static inner class

I've got the following class:

public class A {
    private static class B {
        private static final B instance = new B();
        private ArrayMap<String, Integer> map;
    }
}

I'm trying using reflection to obtain the map field, but I don't understand what to do. My current code is:

    Class<?>[] classes = ainstance.getClass().getDeclaredClasses();
    for (Class c : classes) {
        if (c.getName().equals("com.foo.A$B")) {
            try {
                Field f = c.getDeclaredField("instance");
                f.setAccessible(true);
                Field f1 = c.getDeclaredField("map");
                f1.setAccessible(true);
                ArrayMap<String, Integer> map;
                try {
                    map = (ArrayMap<String, Integer>) f1.get(f.getType());
                    System.out.println(map.get("id"));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    }





Aucun commentaire:

Enregistrer un commentaire