检查类型参数是否是特定接口

Tar*_*rik 2 java factory

我正在写一个看起来像这样的工厂类:

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

Sot*_*lis 8

您需要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.