java 访问私有成员,在Java中访问私有方法?
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.
解決方案
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)
總結
以上是生活随笔為你收集整理的java 访问私有成员,在Java中访问私有方法?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java not found_java_
- 下一篇: java jnlp被阻止_JNLP应用程