-7

如何实现这样的功能来访问私有成员?

Java 仅在编译期间检查访问权限。你惊喜吗?得知这个事实,我感到非常惊讶。

所以你可以创建第三方类的骨架(即使是空的实现)。有趣的方法应该被保护而不是私有。现在编写您的子类并针对您的存根进行编译。然后只打包您的子类并尝试使用“真实”类运行它。它应该工作。当我不得不访问私有方法或字段时,我已经尝试过了,它对我来说效果很好。

参考。https://stackoverflow.com/a/4440051/1312423

4

1 回答 1

3

Java 仅在编译期间检查访问权限。你惊喜吗?

是的,因为它也在运行时检查访问修饰符。


我从

public class AnotherClass {
    protected static void printMe() {
        System.out.println("Hello World");
    }
}

public class Main {
    public static void main(String... args) {
        AnotherClass.printMe();
    }
}

它编译并运行。

如果我在不重新编译的情况下将其更改printMe()为确实可以编译,但是当我运行时我得到了。privateMainMain

Exception in thread "main" java.lang.IllegalAccessError: tried to access method AnotherClass.printMe()V from class Main
    at Main.main(Main.java:22)
于 2012-10-10T10:48:50.413 回答