遇到个需求,需要扫描所有子类,在网上找到的资料都是使用org.reflections.Reflections进行扫描,但是在我的项目中死活扫描不全,还没有找到原因(相关代码单独放到一个项目中就没有扫描不全的现象,在项目中只要使用到了Lambda表达式的类就无法被扫描到),因此替换为使用spring相关功能扫描,具体代码如下:
public static <T> Set<Class<? extends T>> getSubTypesOf(Class<T> type) {
return new resourceScanner().findResource(type);
}
private static class resourceScanner extends ClassPathScanningCandidateComponentProvider {
public <T> Set<Class<? extends T>> findResource(Class<T> type) {
Set<Class<? extends T>> result = new HashSet<>();
super.setEnvironment(new StandardEnvironment());
super.setResourceLoader(new DefaultResourceLoader());
String basePackage = type.getPackage().getName();
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
String resourcePattern = "*/*.class";
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + '/' + resourcePattern;
String baseClassName = type.getName();
try {
Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
for (Resource resource : resources) {
ClassMetadata classMetadata = getMetadataReaderFactory().getMetadataReader(resource).getClassMetadata();
if (baseClassName.equals(classMetadata.getSuperClassName())) {
Class<?> aClass = Class.forName(classMetadata.getClassName());
result.add((Class<? extends T>) aClass);
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return result;
}
}
参考Spring源码阅读(一):Spring是如何扫描某个包下面所有的类 | 赵岩的博客 (zhaoyanblog.com)
网友评论