使用的是Spring提供的工具:ClassPathScanningCandidateComponentProvider
获取包下所有类(包含子包),匹配任何类
public static List<Class<?>> getClasssFromPackage(String... packges)
{
final List<Class<?>> clazzs = new ArrayList<>();
for (String packge : packges)
{
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new TypeFilter()
{
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException
{
String className = metadataReader.getClassMetadata().getClassName();
try
{
Class<?> clazz = Class.forName(className);
clazzs.add(clazz);
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
return true;
}
});
provider.findCandidateComponents(packge);
}
return clazzs;
}
带过滤的匹配
public static void main(String[] args) throws ClassNotFoundException
{
// true:默认TypeFilter生效,这种模式会查询出许多不符合你要求的class名
// false:关闭默认TypeFilter
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
false);
// 扫描带有自定义注解的类
provider.addIncludeFilter(new AnnotationTypeFilter(ScanAnnotation.class));
// 接口不会被扫描,其子类会被扫描出来
provider.addIncludeFilter(new AssignableTypeFilter(ScanClassInterface.class));
// Spring会将 .换成/ ("."-based package path to a "/"-based)
// Spring拼接的扫描地址:classpath*:xxx/xxx/xxx/**/*.class
// Set<BeanDefinition> scanList = provider.findCandidateComponents("com.p7.demo.scanclass");
Set<BeanDefinition> scanList = provider.findCandidateComponents("*");
for (BeanDefinition beanDefinition : scanList)
{
System.out.println(beanDefinition.getBeanClassName());
}
}