简体   繁体   中英

Java annotations: dynamically build array based on annotated fields

I have to @Override an abstract function and offer an array of strings (defining searchable fields for my datatable):

@Override
public String[] getQueryFields() {
    return new String[] { "email", "firstname", "lastname", "lastLogin"};
}

When I look on my code I could imagine that I just reference a class and annotate the JPA column fields, eg by @Searchable to signal this capability and build my array:

@Column
@Getter
@Setter
...
@Searchable
private String email;

Is there a way to handle this?

You can certainly do anything that you want with Reflection. but you should try and explore for other options too. Here is aa crude example i just wrote. it will give you the fields that are annotated by @AnAnnotation .

@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface AnAnnotation {

}


public class AnnotExample {

   @AnAnnotation
   private String b;

   @AnAnnotation
   private String c;

   public static void getAnnotatedFields(final Class clazz) {
      clazz.getAnnotation(AnAnnotation.class);

      final Field[] declaredFields = clazz.getDeclaredFields();
      for (final Field field : declaredFields) {
         final AnAnnotation annotation2 = field.getAnnotation(AnAnnotation.class);
         if (annotation2 != null) {
            System.out.println(field.getName());
         }

      }
   }

   public static void main(final String[] args) {
      AnnotExample.getAnnotatedFields(AnnotExample.class);
   }

}

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