• 第三方反射工具包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;
        	}
        	
            // ...
        }
      

    参考

  • 相关阅读:
    Codeforces Round #362 (Div. 2) C
    poj1655 树重心
    poj1985 树直径
    Codeforces Round #403 (based on Technocup 2017 Finals)
    uva 10054 The necklacr
    bfs codeforces 754B Ilya and tic-tac-toe game
    矩阵快速幂专题
    CodeForces 863E Turn Off The TV 思维,扫描线
    CodeForces 803F Coprime Subsequences 莫比乌斯,容斥
    CodeForces 803C Maximal GCD 思维
  • 原文地址:https://www.cnblogs.com/summaster/p/15594329.html
Copyright © 2020-2023  润新知