Accesing Private Methods in java? [closed]

Deadly 提交于 2019-12-13 10:13:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!