gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:30:21 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com