If I create an anonymous class with a private method, and try to access the method using reflection, it will throw an IllegalAccessException. However, if I call the method on the object before saving it to a variable, it works fine:
public class Z {
public static void main(String[] args) throws Exception {
Object obj = new Object(){private void foo(){}};
obj.getClass().getDeclaredMethod("foo").invoke(obj); // throws IllegalAccessException
new Object(){private void foo(){}}.foo(); // works
}
}
What's the reason for the difference?
Aucun commentaire:
Enregistrer un commentaire