简体   繁体   中英

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.

How can I solve this problem?

XMLRoutine has private constructor. So you can't create using new 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

The constructor is private. So you cannot instantiate it the normal way with new XMLRoutine() .

If it has the public static getInstance() method then you can use that one instead in order to instantiate the class.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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