利用Spring的包扫描代码,实现自定义包扫描, 代码可直接使用
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
/**
* @author Adam
* @version 1.0
* @date 2015-10-30
*/
public class ClassScanner {
private static final Logger logger = LoggerFactory.getLogger(ClassScanner.class);
public static List<Class> scan(String scanPackage) {
List<Class> clazzs = new LinkedList<Class>();
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(scanPackage) + "/**/*.class";
try {
// 扫描包 然后加载class
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resourcePatternResolver.getResources(pattern);
MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader reader = readerFactory.getMetadataReader(resource);
String className = reader.getClassMetadata().getClassName();
logger.info("scanned class {}", className);
Class clazz = Class.forName(className);
clazzs.add(clazz);
}
}
} catch (ClassNotFoundException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return clazzs;
}
}
Q.E.D.