【记录】利用java反射技术扫描包中包含某注解 类集合
public static List<Class> scanClass(String classPath, Class<? extends Annotation> annotation) { List<Class> classList = new ArrayList<>(); if (ObjectUtils.isEmpty(classPath)) { return classList; } ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); TypeFilter includeFilter = (metadataReader, metadataReaderFactory) -> true; provider.addIncludeFilter(includeFilter); Set<BeanDefinition> beanDefinitionSet = new HashSet<>(); // 指定扫描的包名 Set<BeanDefinition> candidateComponents = provider.findCandidateComponents(classPath); beanDefinitionSet.addAll(candidateComponents); beanDefinitionSet.forEach(beanDefinition -> { GenericBeanDefinition definition = (GenericBeanDefinition) beanDefinition; try { Class clazz = Class.forName(beanDefinition.getBeanClassName()); if (!ObjectUtils.isEmpty(annotation)) { if (!ObjectUtils.isEmpty(AnnotationUtils.getAnnotation(clazz, annotation))) { classList.add(clazz); } } else { classList.add(clazz); } } catch (ClassNotFoundException e) { e.printStackTrace(); } // System.out.println(definition.getBeanClassName()); }); return classList; }