用 hutool 的 ClassUtil.scanPackage
举例
public static void test1() {
Set<Class<?>> clazzList = ClassUtil.scanPackage("com.kedu.scm", Class::isEnum);
for (Class<?> clazz : clazzList) {
System.out.println(clazz);
Object[] enumConstants = clazz.getEnumConstants();
Arrays.stream(enumConstants).forEach(System.out::println);
}
}
运行结果
class com.fangye.base.enums.YesOrNoEnum
YES
NO
利用spring自写scanPackage
package com.fangye.base.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
/**
* class 工具类
*
* @author qizenan
* @date 2023/07/13
*/
@Slf4j
public class ClassUtil {
/**
* 扫描包,获取指定class的集合
*
* @param basePackage 基本包
* @param filter 过滤器
* @return {@link List}<{@link Class}<{@link ?}>>
*/
public static List<Class<?>> scanPackage(String basePackage, Predicate<Class<?>> filter) {
List<Class<?>> classList = new ArrayList<>();
if (StringUtils.isEmpty(basePackage)) {
return classList;
}
basePackage = basePackage.replace(".", "/") + "/";
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + basePackage + "**/*.class";
try {
// 对 basePackage 包进行扫描
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
if (resources.length == 0) {
return classList;
}
MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
for (Resource resource : resources) {
if (!resource.isReadable()) {
continue;
}
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
Class<?> clazz = Class.forName(metadataReader.getClassMetadata().getClassName());
if (filter != null && !filter.test(clazz)) {
continue;
}
classList.add(clazz);
}
} catch (Exception e) {
log.info("扫描 package 失败", e);
}
return classList;
}
}
测试文章来源:https://www.toymoban.com/news/detail-559933.html
public static void main(String[] args) {
List<Class<?>> clazzList = scanPackage("com.fangye.base", Class::isEnum);
for (Class<?> clazz : clazzList) {
System.out.println(clazz);
Object[] enumConstants = clazz.getEnumConstants();
Arrays.stream(enumConstants).forEach(System.out::println);
}
}
运行结果文章来源地址https://www.toymoban.com/news/detail-559933.html
class com.fangye.base.enums.YesOrNoEnum
YES
NO
到了这里,关于扫描class的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!