[英]How to exclude scanning of beans that annotated with specific annotation and not annotated with another annotation?
[英]how to find field that annotated with specific annotation by reflection?
當注釋具有值時,如何找到使用注釋進行注釋的字段?
例如,我想在一個實體中找到一個注釋的字段
@customAnnotation( name = "field1" )
private String fileName ;
有沒有辦法直接通過反射(java反射或反射庫)找到這個字段(例如fileName)而不使用循環和比較?
是的,有一個很好的圖書館。
<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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.