1

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?

crush
  • 16,713
  • 9
  • 59
  • 100
  • You could consider the [spring framework](http://static.springsource.org/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-instantiation) for this.. – pd40 Feb 20 '13 at 02:13

1 Answers1

0

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.

Community
  • 1
  • 1
Romski
  • 1,912
  • 1
  • 12
  • 27
  • How do I call the constructor with parameters using the `Class.forName` – crush Feb 20 '13 at 03:15
  • I want to be able to make the parameters dynamic based on whats in the config file. I think I can do it with a variation of this, so I'll make this as the answer. – crush Feb 20 '13 at 22:48