Reputation: 187
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?
Upvotes: 1
Views: 1443
Reputation: 3778
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 ...
}
Upvotes: 0
Reputation: 2143
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();
Upvotes: 0
Reputation: 720
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
Upvotes: 5