I'd like for a subclass of a certain superclass with certain constructor parameters to load an XML file containing information that I'd then like to pass to the superconstructor. Is this impossible to achieve?
views:
186answers:
6How about using a factory method instead? Maybe something like:
private MyObject(ComplexData data)
{
super(data);
}
public static MyObject createMyObject(String someParameter)
{
ComplexData data = XMLParser.createData(someParameter);
return new MyObject(data);
}
You can call a static method in the super() call, e.g.
public Subclass(String filename)
{
super(loadFile(filename));
}
private static byte[] loadFile(String filename)
{
// ...
}
In order to load the XML you need a valid subclass object, which requires a valid superclass object 'in it'. So what you want is impossible.
I like the factory answer, but you can sometimes also do something like:
public MyObject(String parm) {
super(parseComplex(parm));
}
private static ComplexData parseComplex(String parm) {
....
return new ComplexData(...);
}
Impossible, no. Messy, potentially very.
I've needed to do this before and found that the easiest cleanest way and to handle it is to load the data before calling the constructor and then pass it as an argument.
I like mathews suggestion. A variation of this is to create objects that managed to preloaded data, and pass those into the constructor of the object.
I doing this in a project I'm working on for a client. Theres a bunch of configuration files that need to be loaded. I also have database and webservice connections that need to be established before dependent objects can be constructed.
It works great, its simple, and when someone else inherits this code it will be simple for them to follow the logic. This improves the value for the client.