扫描并实例化约定包下的子类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;
}
// ...
}