【问题标题】:Check if a type parameter is a specific interface [duplicate]检查类型参数是否是特定接口[重复]
【发布时间】:2013-12-17 04:51:59
【问题描述】:

我正在编写一个如下所示的工厂类:

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 实例传递给getRepository()

标签: java factory


【解决方案1】:

您需要通过传入泛型类型的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,所以我不知道该怎么做。
猜你喜欢
  • 2019-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
  • 2021-12-26
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多