温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中怎么获取接口的所有实现类

发布时间:2021-08-07 11:39:11 来源:亿速云 阅读:538 作者:Leah 栏目:编程语言

本篇文章给大家分享的是有关Java中怎么获取接口的所有实现类,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

1.借助Spring容器实现

Spring作为一个容器,管理着一个项目中所有经过配置的Java类(xml配置文件或Annotation方式)。如果某个接口的所有实现类均被Spring托管了,那么通过Spring就可以很简单的返回这些实现类。

import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;@Componentpublic class ServiceLocator implements ApplicationContextAware{  /**   * 用于保存接口实现类名及对应的类   */  private Map<String, IService> map;  /**   * 获取应用上下文并获取相应的接口实现类   * @param applicationContext   * @throws BeansException   */  @Override  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {    //根据接口类型返回相应的所有bean    Map<String, IService> map = applicationContext.getBeansOfType(IService.class);  }  public Map<String, IService> getMap() {    return map;  }}

2.借助ServiceLoader类

ServiceLoader是JDK自带的一个类加载器,位于java.util包当中,作为 A simple service-provider loading facility. 具体使用方式如下:

1.在META-INF/services/目录下用你的接口全路径名称命名一个文件(不加后缀),然后在该文件中一行一个添加你的接口实现类的全路径名。

2.通过load方法来加载出所有的接口实现类

ServiceLoader<MyInterface> loader = ServiceLoader.load(MyInterface.class);

在这里load方法的返回值是一个迭代器,用这个迭代器可以遍历出所有的接口实现类。

以上就是Java中怎么获取接口的所有实现类,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI