importjava.io.IOException;importjava.util.HashSet;importjava.util.Set;importorg.springframework.context.ResourceLoaderAware;importorg.springframework.context.annotation.Configuration;importorg.springframework.core.io.Resource;importorg.springframework.core.io.ResourceLoader;importorg.springframework.core.io.support.PathMatchingResourcePatternResolver;importorg.springframework.core.io.support.ResourcePatternResolver;importorg.springframework.core.io.support.ResourcePatternUtils;importorg.springframework.core.type.classreading.CachingMetadataReaderFactory;importorg.springframework.core.type.classreading.MetadataReader;importorg.springframework.core.type.classreading.MetadataReaderFactory;importorg.springframework.util.ClassUtils;importorg.springframework.util.SystemPropertyUtils;/*** 扫描类工具
*
* @project common-utils
* @fileName ScanerUtil.java
* @Description
*@authorlight-zhang
* @date 2019年4月12日
*@version1.0.0*/@Configurationpublic class ScanerUtil implementsResourceLoaderAware {private ResourcePatternResolver resourcePatternResolver = newPathMatchingResourcePatternResolver();private MetadataReaderFactory metadataReaderFactory = newCachingMetadataReaderFactory(resourcePatternResolver);
public static Set>scanner() {try{String scanPath="cc.xx.mall.common.fulltext";return newScanerUtil().doScan(scanPath);
}catch(Exception e) {
}return null;
}public Set> doScan(String scanPath) throwsIOException {
Set> classes = new HashSet>();
String packageSearchPath=ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
.concat(ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(scanPath))
.concat("/**/*.class"));
Resource[] resources=resourcePatternResolver.getResources(packageSearchPath);
MetadataReader metadataReader= null;for(Resource resource : resources) {if(resource.isReadable()) {
metadataReader=metadataReaderFactory.getMetadataReader(resource);try{if (metadataReader.getClassMetadata().isConcrete()) {//当类型不为抽象类或接口在添加到集合
classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
}
}catch(Exception e) {
e.printStackTrace();
}
}
}returnclasses;
}
@Overridepublic voidsetResourceLoader(ResourceLoader resourceLoader) {this.resourcePatternResolver =ResourcePatternUtils.getResourcePatternResolver(resourceLoader);this.metadataReaderFactory = newCachingMetadataReaderFactory(resourceLoader);
}public static voidmain(String[] args) {
Set> clazz =ScanerUtil.scanner();for (Class>class1 : clazz) {
System.out.println(class1.getName());
}
}
}