繁体   English   中英

java从私有类调用public方法

[英]java call public method from private class

我需要像这样从库中的公共类调用私有构造函数:

public class XMLRoutine {
    private static XMLRoutine _instance;
    private XMLRoutine() {
    }
    public String signXml(String xml, PrivateKey privateKey, Certificate cert, String encoding) throws ParserConfigurationException, SAXException, IOException, PrivilegedActionException {
    }
}

当我尝试这样称呼它时:

import kz.softkey.iola.applet.XMLRoutine;
...
XMLRoutine xmlr = new XMLRoutine();

我收到一个错误: XMLRoutine() has private access in XMLRoutine ,因此我无法调用方法signXml。

我怎么解决这个问题?

XMLRoutine具有私有构造函数。 因此,您不能使用新的XMLRoutine()创建。 它可能具有用于创建新的单例对象的getInstance()方法或一些其他静态方法(可用于创建同一类的对象)

构造函数是私有的。 因此,您无法使用new XMLRoutine()正常实例化它。

如果它具有公共静态getInstance()方法,则可以改用该方法实例化该类。

XMLRoutine xmlRoutine = XMLRoutine.getInstance();
String res = xmlRoutine.anyPublicMethod();

您需要考虑到构造函数私有的原因。 这很可能是因为您不应该直接实例化该类。

如果您确实需要实例化它,而又没有其他处理方法,则可以随时恢复反射(同样,请首先穷尽所有其他选项)。

尝试以下方法:

try {
    Class<?> cls = XMLRoutine.class;
    Constructor<XMLRoutine> constructor = cls.getDeclaredConstructor();
    constructor.setAccessible(true);
    XMLRoutine xmlRouting = constructor.newInstance();
} catch (Exception e) { // Change to specific exception types being thrown from reflection
    // handle error ...
}

暂无
暂无

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

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