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?
In the first case, you're trying to access the method by reflection, and since it is a private method, the reflector class cannot invoke it, thus it throws an IllegalAccessException
.
In the second case, you're accessing the method directly, and you're allowed to since because it is an anonymous inner class to Z
and you're accessing it inside Z
class.