mardi 5 juillet 2016

Reflection to access values that are nested classes

I know it is bad code design, but as a temporary hack...

I need to access a private map where the values are initializations of a static nested class. In the following example, I want to access each value of myMap from a different package.

package belongs.to.someone.else

public class SOExample {
    private Map<String, NestedClass> myMap;

    static class NestedClass {
        final int data;
        NestedClass(final int data) {
            this.data = data;
        }
    }

    public void populateMyMap(){
        for(int i=0; i<100;  i++){
            this.myMap.put(Integer.toString(i), new NestedClass(i));
        }
    }
}

But I seem to run into a chicken and egg problem when trying to set the SOExample.myMap field to accessible. I get "cannot be accessed from outside of package" error for the SOExample.NestedClass values in the last statement.

package belongs.to.me
public class SOExampleMyPackage {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        SOExample example = new SOExample();
        example.populateMyMap();

        // Make the example.myMap field accessible
        Field f = example.getClass().getDeclaredField("myMap");
        f.setAccessible(true);
        // Next line throws error
        Map<String, SOExample.NestedClass> myMapHere = (Map<String, SOExample.NestedClass>) f.get(example);
    }
}

I appreciate any ideas about how to solve this problem.





Aucun commentaire:

Enregistrer un commentaire