greywolf82 greywolf82 - 3 months ago 11
Java Question

Reflection get field of singleton static nested 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();
}
}
}

Answer

After

            Field f = c.getDeclaredField("instance");
            f.setAccessible(true);

one needs to get the instance object:

            Object instance = f.get(null); // null as static, no 'this'.

Then the same for map, now not with null, but instance.

                map = (ArrayMap<String, Integer>) f1.get(instance);

One could drop the generic type parameters.

Comments