【问题标题】:Java configuration file instantiate object with parametersJava配置文件用参数实例化对象
【发布时间】:2013-02-20 01:43:38
【问题描述】:

我正在尝试找到一种方法,可以在配置文件中指定一个类,以及应该传递给构造函数的参数。

例如,想象以下 XML 配置文件:

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

现在,在我的 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.
        );
    }
}

我当然可以读取 XML,并从中获取值,但是我不确定如何使用 XML 配置文件中的值的注释来模拟上面指示的行(想要替换...) .有没有办法做这样的事情?

【问题讨论】:

标签: java xml configuration


【解决方案1】:

解析配置文件以获取您要使用的类的名称,并使用Class.forName("com.mydomain.server.auth.DefaultAuthenticator") 将其传递给构造函数。如果要传递其他信息,请使用更多参数或属性对象,或类似的。

更多interesting uses 见这个类似问题

编辑

这是你要找的吗?

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

Class.forName 只会调用无参数的默认构造函数。如果您需要提供参数,您可以按照creating objects from constructors using reflection 的 Java 教程使用反射。但是,使用默认构造函数创建实例,然后根据需要使用 setter 进行配置是完全可能的(并且可能更易于阅读)。

【讨论】:

  • 如何使用Class.forName调用带参数的构造函数
  • 我希望能够根据配置文件中的内容使参数动态化。我想我可以用这个变体来做到这一点,所以我会把这个作为答案。
猜你喜欢
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 2013-03-29
  • 2023-03-13
  • 1970-01-01
相关资源
最近更新 更多