简体   繁体   中英

Is it impossible to perform initialization before calling a superclass's constructor?

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?

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); 
}

You can call a static method in the super() call, eg

public Subclass(String filename)
{
    super(loadFile(filename));
}

private static byte[] loadFile(String filename)
{
    // ...
}

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 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(...);
}

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.

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