lundi 23 novembre 2015

reflect public fields of anonymous class from outer package [duplicate]

This question already has an answer here:

I want to access public fields of an anonymous class. Lets say for printing all definied public strings. Have a look at this code.

public class Test {         
    public <T> Test(T obj){     
        // print all public Strings
        Class<?> clazz = obj.getClass();
        for ( Field field : clazz.getFields() ) {
            if(field.getType().isAssignableFrom(String.class)){
                try {
                    String s = (String) field.get(obj);
                    System.out.println(s);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }   
    public static void main(String[] args){
        new Test(new Object(){
            public String s = "hello";
        });
    }
}

It prints "hello", no problem so far.
BUT if I separate the class Test from the main method into a package I get the following runtime exception:

java.lang.IllegalAccessException: Class foo.Test can not access a member of class TestMain$1 with modifiers "public" 

If I don't use an anonymous class it works again.
How can I access public fields of anonymous class from outer package?





Aucun commentaire:

Enregistrer un commentaire