簡體   English   中英

Java配置文件使用參數實例化對象

[英]Java configuration file instantiate object with parameters

我試圖找到一種方法,可以在配置文件中指定類,以及應傳遞給構造函數的參數。

例如,設想以下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配置文件中的值用注釋來模仿上面指出的行(想要替換...)。 有沒有辦法做這樣的事情?

解析配置文件以獲取要使用的類的名稱,然后使用Class.forName("com.mydomain.server.auth.DefaultAuthenticator")將其傳遞給構造函數。 如果要傳遞其他信息,請使用更多參數或屬性對象或類似對象。

看到類似的問題以獲得更有趣的用途

編輯

這是你想要的?

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

Class.forName將僅調用no參數的默認構造函數。 如果需要提供參數,則可以按照Java教程中的說明使用反射,以使用反射從構造函數創建對象 但是,完全有可能(並且可能更易於閱讀)使用默認構造函數創建實例,然后根據需要使用設置器對其進行配置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM