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

 我还是看好小棠呀 发布于 2023-02-09 22:25

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

public class RepositoryFactory {
    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 个回答
  • 您需要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.

    2023-02-09 22:47 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有