在Java中访问私有方法? [英] Accesing Private Methods in java?

查看:398
本文介绍了在Java中访问私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现访问私人会员的功能?

how to implement such a functionality to access private members ?

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

Java checks access permissions during compilation only. Are you surprised? I was surprised very much to find out this fact.

因此,您可以创建第三方类的框架(即使使用空的实现.).有趣的方法应该保护而不是私有.现在编写您的子类,并根据存根对其进行编译.然后只打包您的子类,并尝试使用"real"类运行它.它应该工作. 当我不得不访问私有方法或字段时,我已经尝试过了,它对我来说很好用.

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.

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

推荐答案

Java仅在编译期间检查访问权限.你感到惊讶吗?

Java checks access permissions during compilation only. Are you surprised?

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

Yes, because it checks the access modifier at runtime as well.

我从

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

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

它会编译并运行.

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

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中访问私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆