tags:

views:

186

answers:

6

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?

+12  A: 

How 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); 
}
Outlaw Programmer
Shouldn't the factory method be static?
William Brendel
Whoops, yeah. Funny, you sound just like my compiler!
Outlaw Programmer
I'll try that. Thanks!
Lucas Lindström
+7  A: 

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)
{
    // ...
}
Jon Skeet
A: 

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'd like for a subclass to load" was the question
A: 

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(...);
}
Darron
I feel using a factory is a bit of overkill here, if the purpose is just to be able to parse a ComplexData from XML (or anything else for that matter). So I think your approach is better. Do you actually prefer it over static method? Why?
Hemal Pandya
The factory method is more flexible, it can work if you need to produce multiple arguments for the super() call as the result of your processing.
Darron
+1  A: 

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.

Matthew Brubaker
+1 unless its your classes job to parse the XML, which in this case it doesn't look like it is
MrWiggles
A: 

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.

Conan