简体   繁体   中英

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

How can I find a field that is annotated with annotation when the annotation has a value?

For example I want to find a field in an entity that is annotated with

@customAnnotation( name = "field1" )
private String fileName ;

Is there any way to find this field (fileName in example) directly by reflection (java reflection or reflection library ) and not use the loop and the comparison?

Yes there is a good library .

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

And in your code use the reflections like below:

//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 "";
}

and consume like:

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM