通过 Spring 提供的Api ResourcePatternResolver 读取指定classpath下面的类信息。
示例代码:
import org.junit.Test;
import org.springframework.core.annotation.AnnotationUtils;
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.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.SystemPropertyUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import static org.springframework.core.io.support.ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX;
/**
* @desc: Desc
* @author: wangyingjie1
* @date: 2018/1/29 18:16
* To change this template use File | Settings | File and Code Templates | Includes | File Header.
*/
public class ResourcePatternResolverTest {
private static final String basePackage = "com.jd.controller";
public static final String DEFAULT_RESOURCE_PATTERN = "/**/*";
@Test
public void testReadResource() throws IOException {
//获取Spring资源解析器
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
//获取packageSearchPath下的Resource,这里得到的Resource是Class信息
Resource[] resources = resourcePatternResolver.getResources(CLASSPATH_ALL_URL_PREFIX
+ ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage))
+ DEFAULT_RESOURCE_PATTERN + ClassUtils.CLASS_FILE_SUFFIX);
Arrays.stream(resources).forEach(resource -> {
System.out.println("=======>" + resource.getFilename());
});
parseClazz(resources, resourcePatternResolver);
}
private void parseClazz(Resource[] resources, ResourcePatternResolver resourcePatternResolver) throws IOException {
//创建Spring中用来读取class的工厂
MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
for (Resource resource : resources) {
//检查resource,
String fullClassName = null;
if (resource.isReadable()) {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
if (metadataReader != null) {
fullClassName = metadataReader.getClassMetadata().getClassName();
}
}
try {
Class<?> clazz = Class.forName(fullClassName);
//方式1
Annotation myAnnotation = clazz.getAnnotation(Controller.class);
//方式2
Controller annotation = AnnotationUtils.findAnnotation(clazz, Controller.class);
System.out.println("an===========>" + annotation );
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(" check package path", e);
}
}
}
}