java - 检查类型参数是否是特定接口(interface)

标签 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 的类型?

最佳答案

您需要通过传入泛型类型的 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/

相关文章:

java - 在 Java 中绘制数据并使用余弦进行最小二乘回归

PHP:松耦合参数化工厂。是否可以?

java - 将 Eclipse 安装移动到用户配置文件之外的文件夹?

java - 无法执行目标 org.apache.maven.plugins :maven-archetype-plugin:2. 4:generate

java - 如何在自定义适配器中使用数组?

java - Hibernate 版本控制/乐观锁定本身是否会使实例变脏

angularjs - 更新服务内的范围值

具有 move 语义的 C++ 可变工厂导致运行时崩溃

java - Builder Factory 返回不同的子接口(interface)

c++ - 工厂设计模式如何处理不同长度的构造函数?