如何通过反射找到带有特定注释的字段?

how to find field that annotated with specific annotation by reflection?

注解有值时,如何找到注解有注解的字段?

例如,我想在一个实体中找到一个用

注释的字段
@customAnnotation( name = "field1" )
private String fileName ;

有没有办法直接通过反射(java反射或反射库)找到这个字段(例如fileName)而不使用循环和比较?

是的,有一个很好的library

<dependency>
  <groupId>org.reflections</groupId>
  <artifactId>reflections</artifactId>
  <version>0.9.11</version>
</dependency>

并在您的代码中使用如下反射:

//CustomAnnotation.java

package com.test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
    String name() default "";
}

并像这样消费:

Reflections reflections = new Reflections("com.test", new FieldAnnotationsScanner());
Set<Field> fields = reflections.getFieldsAnnotatedWith(CustomAnnotation.class);

for(Field field : fields){
  CustomAnnotation ann = field.getAnnotation(CustomAnnotation.class);
  System.out.println(ann.name());
}