问题
how to implement such a functionality to access private members ?
Java checks access permissions during compilation only. Are you surprised? I was surprised very much to find out this fact.
So you can create skeleton of the third party class (even with empty implementations.). The interesting method should be protected instead of private. Now write your subclass and compile it against your stub. Then package only your subclass and try to run it with the "real" class. It should work. I have tried it when I had to access private method or field and it worked fine for me.
ref. https://stackoverflow.com/a/4440051/1312423
回答1:
Java checks access permissions during compilation only. Are you surprised?
Yes, because it checks the access modifier at runtime as well.
I start with
public class AnotherClass {
protected static void printMe() {
System.out.println("Hello World");
}
}
public class Main {
public static void main(String... args) {
AnotherClass.printMe();
}
}
and it compiles and runs.
If I change the printMe()
to be private
without re-compiling Main
it does compile but when I run Main
I get.
Exception in thread "main" java.lang.IllegalAccessError: tried to access method AnotherClass.printMe()V from class Main
at Main.main(Main.java:22)
来源:https://stackoverflow.com/questions/12817502/accesing-private-methods-in-java