2013-02-20 34 views
0

我試圖找到一種方法,我可以在配置文件中指定一個類,以及應該傳遞給構造函數的參數。Java配置文件實例化具有參數的對象

例如,假設下面的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配置文件的值的註釋。有沒有辦法做這樣的事情?

+0

你可以考慮[spring framework](http://static.springsource.org/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-instantiation)。 – pd40 2013-02-20 02:13:36

回答

0

解析配置文件以獲取要使用的類的名稱,並使用Class.forName("com.mydomain.server.auth.DefaultAuthenticator")將其傳遞給構造函數。如果你想傳遞額外的信息,那麼使用更多的參數或屬性對象或類似的東西。

的看到這個類似的問題更interesting uses

編輯

這是你在找什麼?

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

Class.forName只會調用no參數的默認構造函數。如果您需要提供參數,您可以按照creating objects from constructors using reflection的Java教程使用反射。但是,使用默認構造函數創建實例並使用setter來根據需要進行配置是完全可能的(也可能更易於閱讀)。

+0

如何使用'Class.forName'通過參數調用構造函數 – crush 2013-02-20 03:15:23

+0

我希望能夠根據配置文件中的內容使參數動態化。我想我可以用這種變化來做到這一點,所以我會以此作爲答案。 – crush 2013-02-20 22:48:28