2013-12-17 55 views
2

我寫一個工廠類,看起來像這樣:檢查一個類型參數是一個特定的接口

public class RepositoryFactory<T> { 
    public T getRepository(){ 
     if(T is IQuestionRepository){ // This is where I am not sure 
      return new QuestionRepository(); 
     } 
     if(T is IAnswerRepository){ // This is where I am not sure 
      return new AnswerRepository(); 
     } 
    } 
} 

,但我怎麼能檢查T是一種類型的指定interface

+0

你不能。將'Class'實例傳遞給'getRepository()'。 –

回答

8

您需要通過傳入Class對象來創建泛型類型的RepositoryFactory實例。

public class RepositoryFactory<T> { 
    private Class<T> type; 
    public RepositoryFactory(Class<T> type) { 
     this.type = type; 
    } 
    public T getRepository(){ 
     if(type.isAssignableFrom(IQuestionRepository.class)){ //or type.equals(...) for more restrictive 
      return new QuestionRepository(); 
     } 
     ... 
    } 

否則,在運行時,你可以不知道類型變量T的價值。

+0

很好的答案,謝謝!我仍然在學Java,所以我不知道該怎麼做。 – Tarik

相關問題