简体   繁体   English

如何从java中的不同类访问私有类的公共方法?

[英]How can you access public methods from private class from a different class in java?

I just have a question, is there any way to access public methods from a class which is private from a different class? 我只是有一个问题,有没有办法从一个来自不同类的私有类访问公共方法? For Example the print method can be accessed from a different class since the class is private? 例如,可以从不同的类访问print方法,因为该类是私有的?

private class TestClass {
    public void print() {
    }
}

Yes there is. 就在这里。

You don't actually return an direct reference to your private class, since other classes can't use it. 您实际上并没有返回对您的私有类的直接引用,因为其他类不能使用它。 Instead, you extend some public class, and return your private class as an instance of that public class. 相反,您扩展了一些公共类,并将您的私有类作为该公共类的实例返回。 Then any methods it inherited can be called. 然后可以调用它继承的任何方法。

public interface Printable {
    void print();
}

public class Test {
    public Printable getPrintable() {
        return new PrintTest();
    }

    private class PrintTest implements Printable {
        public void print() {
        }
    }
}

Test test = new Test();
test.getPrintable().print();

You can do that by extending that class with a public class. 您可以通过使用公共类扩展该类来实现。 Or you can always use reflection! 或者你总是可以使用反射!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM