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

时间:2013-12-17 04:52:00

标签: 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();
        }
    }
}

但如何查看T是指定interface的类型?

1 个答案:

答案 0 :(得分: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();
        }
        ...
    }

否则,在运行时,您无法知道类型变量T的值。