我正在编写一个工厂类,如下所示:
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
的类型?
最佳答案
您需要通过传入泛型类型的 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
的值。
关于java - 检查类型参数是否是特定接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626170/