2013-12-17 56 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

相关问题