直接上代码:
@Test void contextLoads() throws IOException, ClassNotFoundException { //spring 工具类可以获取指定路径表的全部类 PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //监听的包如下: String basePackage = "com.chen.jwt.controller"; String resourcePattern = "/**/*.class"; String pattern = resolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils .convertClassNameToResourcePath(basePackage) + resourcePattern; //获取包下面指定的类资源 Resource[] resources = resolver.getResources(pattern); //MetadataReader 工厂类 MetadataReaderFactory factory = new CachingMetadataReaderFactory(resolver); for (Resource resource: resources) { //用来读取类的信息 MetadataReader reader = factory.getMetadataReader(resource); //扫描到的class String className = reader.getClassMetadata().getClassName(); //获取到类名 Class<?> clazzName = Class.forName(className); System.out.println(clazzName); //判断类名上是否有 @UserLoginToken 注解 UserLoginToken annotation = clazzName.getAnnotation(UserLoginToken.class); if (annotation != null) { System.out.println("类中的注解:"+ annotation.annotationType().getName()); } }