简体   繁体   中英

Java configuration file instantiate object with parameters

I'm trying to find a way that I can specify a class in a configuration file, as well as the parameters that should be passed to the constructor.

For example, imagine the following XML configuration file:

<AuthServer>
    <Authenticator type="com.mydomain.server.auth.DefaultAuthenticator">
        <Param type="com.mydomain.database.Database" />
    </Authenticator>
</AuthServer>

Now, in my Java code, I want to do the following:

public class AuthServer {
    protected IAuthenticator authenticator;

    public AuthServer(IAuthenticator authenticator) {
        this.authenticator = authenticator;
    }

    public int authenticate(String username, String password) {
        return authenticator.authenticator(username, password);
    }

    public static void main(String[] args) throws Exception {
        //Read XML configuration here.

        AuthServer authServer = new AuthServer(
            new DefaultAuthenticator(new Database()) //Want to replace this line with what comes from the configuration file.
        );
    }
}

I can read the XML of course, and get the values from it, but then I'm unsure how to emulate the line indicated above (want to replace...) with the comment with the values from the XML configuration file. Is there a way to do something like this?

Parse the configuration file to get the name of the class you want to use and pass it to the constructor using Class.forName("com.mydomain.server.auth.DefaultAuthenticator") . If you want to pass additional information, then use more arguments or a properties object, or similar.

See this similar question for more interesting uses

EDIT

Is this what you are looking for?

new DefaultAuthenticator(Class.forName("com.mydomain.server.auth.DefaultAuthenticator").newInstance());

Class.forName will only call the no argument default constructor. If you need to supply arguments you can use reflection as per the Java tutorials for creating objects from constructors using reflection . However, it would be perfectly possible (and possibly easier to read) to create the instance using the default constructor, and then using setters to configure it as you need.

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