第三方反射工具包reflections使用

前言

  • 之前设计通用的经办复核功能时,大面积的进行了抽象和规范定义,于是出现了需要扫描约定包下类的场景。
  • 各种方式尝试后,最终使用第三方Maven库 reflections 很好的实现了效果,记录下demo。

开始

  • maven引入
    <!-- https://mvnrepository.com/artifact/org.reflections/reflections -->
      <dependency>
          <groupId>org.reflections</groupId>
          <artifactId>reflections</artifactId>
          <version>0.9.11</version>
      </dependency>
    
  • 扫描并实例化约定包下的子类demo
    @Data
      @EqualsAndHashCode(callSuper = false)
      @JsonInclude(JsonInclude.Include.NON_NULL)
      @Slf4j
      public abstract class BaseAuditViewDto extends BaseAuditDto {
      	private static final long serialVersionUID = 1L;
      	
      	private static final String prefixPackage = "com.ql.feign";
      	
      	private static Map<AuditBusinessTypeEnum, Class<? extends BaseAuditViewDto>> businessClassMap = new HashMap<>();
      	
      	static {
      		log.info("开始获取所有审核展示数据子类,并注册子类到对应的审核业务");
      		log.info("扫描子路径:{}", prefixPackage);
      		Reflections reflections = new Reflections(prefixPackage);
      		Set<Class<? extends BaseAuditViewDto>> subClazzs = reflections.getSubTypesOf(BaseAuditViewDto.class);
      		for(Class<? extends BaseAuditViewDto> clazz:subClazzs) {
      			try {
      				BaseAuditViewDto newInstance = clazz.newInstance();
      				AuditBusinessTypeEnum[] bizTypess = newInstance.auditBusinessTypePresent();
      				for(int i=0; i<bizTypess.length; i++) {
      					businessClassMap.put(bizTypess[i], clazz);
      				}
      			} catch (InstantiationException | IllegalAccessException e) {
      				log.error("类反射得到类对象异常({})", clazz.getName(), e);
      			}
      		}
      		log.info("完成审核展示数据子类注册:size({}), {}", businessClassMap.size(), businessClassMap);
      	}
      	
      	/**
      	 * 根据审核业务类型获取提交数据的展示类
      	 * @param business
      	 * @return
      	 */
      	public static Class<? extends BaseAuditViewDto> getDataShowQualifiedClass(AuditBusinessTypeEnum business) {
      		Class<? extends BaseAuditViewDto> qualifiedClass = businessClassMap.get(business);
      		return qualifiedClass;
      	}
      	
          // ...
      }
    

参考

posted @ 2021-11-23 17:34  summaster  阅读(930)  评论(0编辑  收藏  举报