简体   繁体   English

检查项目中的所有类是否都有特定的注释

[英]Check, if all classes in project have a specific annotation

My current situation: I want to write a test that checks, if all my files with "Service" in the name have the "@Valid" Annotation.我目前的情况:我想编写一个测试来检查我所有名称中带有“服务”的文件是否都具有“@Valid”注释。 I tried researching it but could not find anything.我尝试研究它,但找不到任何东西。

The Java Reflection API can be used to check the annotations of a class. Java 反射 API可用于检查 class 的注释。

Eg the following code prints the name and value of each class annotation of type MyAnnotation .例如,以下代码打印 MyAnnotation 类型的每个MyAnnotation注释的名称和值。

Class aClass = TheClass.class;
Annotation[] annotations = aClass.getAnnotations();

for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("name: " + myAnnotation.name());
        System.out.println("value: " + myAnnotation.value());
    }
}

source资源

The comment by Lino shows how to find all classes in the current classpath. Lino 的评论显示了如何在当前类路径中查找所有类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java:有没有办法指定具有特定注释的类? - Java: Is there a way to specificy classes that have a specific annotation? 如何找到类路径上具有特定方法注释的所有类? - How can I find all classes on the classpath that have a specific method annotation? 防止在编译时或运行时在项目类中使用特定注释 - Prevent using specific annotation in project classes on compile time or at runtime 我可以为具有特定注释的类创建通用接口吗? - Can I make a generic interface for classes that have a specific annotation? 所有具有特定注释并实现特定接口的类 - all classes which have a certain annotation and implement a certain interface 无法使用 spring ClassPathScanningCandidateComponentProvider 返回所有标有特定注释的类 - Can't return all classes marked with specific annotation using spring ClassPathScanningCandidateComponentProvider 使用特定注释注入所有bean - Inject all beans with a specific annotation 如何在特定程序包中带一些注释的类 - How take classes with some annotation in specific package Java 泛型类型绑定到具有特定注释的类 - Java generic type bounded to classes with specific annotation 在项目中,是否有任何方法可以检查所有步骤是否具有匹配的步骤定义 - In a project, is there any way to check if all the steps have matching step definitions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM