简体   繁体   English

java从私有类调用public方法

[英]java call public method from private class

I need to call a private constructor from a public class from a library like this: 我需要像这样从库中的公共类调用私有构造函数:

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 {
    }
}

When I try to call it like this: 当我尝试这样称呼它时:

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

I get an error: XMLRoutine() has private access in XMLRoutine , so I cant call method signXml. 我收到一个错误: XMLRoutine() has private access in XMLRoutine ,因此我无法调用方法signXml。

How can I solve this problem? 我怎么解决这个问题?

XMLRoutine has private constructor. XMLRoutine具有私有构造函数。 So you can't create using new XMLRoutine(). 因此,您不能使用新的XMLRoutine()创建。 it might have getInstance() method for creating new singleton object or some other static methods that you can use instead of creating the object of the same class 它可能具有用于创建新的单例对象的getInstance()方法或一些其他静态方法(可用于创建同一类的对象)

The constructor is private. 构造函数是私有的。 So you cannot instantiate it the normal way with new XMLRoutine() . 因此,您无法使用new XMLRoutine()正常实例化它。

If it has the public static getInstance() method then you can use that one instead in order to instantiate the class. 如果它具有公共静态getInstance()方法,则可以改用该方法实例化该类。

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

You need to consider that there's a reason for the constructor being private. 您需要考虑到构造函数私有的原因。 It's most probably because you're not supposed to instantiate the class directly. 这很可能是因为您不应该直接实例化该类。

If you do desperately need to instantiate it, and have no other way of doing things, you can always revert to reflection (again, exhaust all other options first). 如果您确实需要实例化它,而又没有其他处理方法,则可以随时恢复反射(同样,请首先穷尽所有其他选项)。

Try something along the lines of: 尝试以下方法:

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