我正在写一个看起来像这样的工厂类:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是如何检查它T是否是指定的类型interface?
您需要RepositoryFactory通过传入Class泛型类型的对象来创建实例.
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();
}
...
}
Run Code Online (Sandbox Code Playgroud)
否则,在运行时,您无法知道类型变量的值T.