public class ReadAnnotationUtils {
private static final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
private static final SimpleMetadataReaderFactory register = new SimpleMetadataReaderFactory();
private static final StandardEnvironment environment = new StandardEnvironment();
public static String getResourcePath(String packagePath) {
if (StringUtils.isEmpty(packagePath)) return "";
String resourcePath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+ ClassUtils.convertClassNameToResourcePath(environment.resolveRequiredPlaceholders(packagePath))
+ '/' + "**
public static Set getClazzFromAnnotation(String pkgPath, Class extends Annotation> annoClazz) {
//擷取spring的包路徑
String pathPackage = getResourcePath(pkgPath);
Set paths = new HashSet<>();
Resource[] resources = new Resource[0];
try {
//加載路徑
resources = resolver.getResources(pathPackage);
} catch (IOException e) {
//異常處理
return new HashSet<>();
}
for (int i = 0; i < resources.length; i++) {
Resource resource = resources[i];
MetadataReader metadataReader = null;
try {
//讀取資源
metadataReader = register.getMetadataReader(resource);
} catch (IOException e) {
continue;
}
//讀取資源的注解配置
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
//判斷是否包含注解
if (!annotationMetadata.hasAnnotation(annoClazz.getName())) continue;
//類資訊
ClassMetadata classMetadata = metadataReader.getClassMetadata();
//類全名
String className = classMetadata.getClassName();
try {
//加載類
Class> clazz = Class.forName(className);
paths.add(clazz);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return paths;
}
public static void main(String[] args) {
//測試
Set clazz = getClazzFromAnnotation("com.pkg.fp", RSPI.class);
System.out.println(clazz);
}
}