简体   繁体   English

Java配置文件使用参数实例化对象

[英]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: 例如,设想以下XML配置文件:

<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: 现在,在我的Java代码中,我想执行以下操作:

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. 我当然可以阅读XML,并从中获取值,但是我不确定如何用XML配置文件中的值用注释来模仿上面指出的行(想要替换...)。 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") . 解析配置文件以获取要使用的类的名称,然后使用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. Class.forName将仅调用no参数的默认构造函数。 If you need to supply arguments you can use reflection as per the Java tutorials for creating objects from constructors using reflection . 如果需要提供参数,则可以按照Java教程中的说明使用反射,以使用反射从构造函数创建对象 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. 但是,完全有可能(并且可能更易于阅读)使用默认构造函数创建实例,然后根据需要使用设置器对其进行配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM