在java中访问私有方法?

时间:2012-10-10 10:44:59

标签: java methods private override

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

Java仅在编译期间检查访问权限。你惊喜吗?我非常惊讶地发现了这个事实。

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

REF。 https://stackoverflow.com/a/4440051/1312423

1 个答案:

答案 0 :(得分: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()更改为private而不重新编译Main它会编译,但是当我运行Main时,我会得到。

Exception in thread "main" java.lang.IllegalAccessError: tried to access method AnotherClass.printMe()V from class Main
    at Main.main(Main.java:22)