John Rumpel
John Rumpel

Reputation: 4615

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, e.g. by @Searchable to signal this capability and build my array:

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

Is there a way to handle this?

Upvotes: 0

Views: 130

Answers (1)

Hrishikesh
Hrishikesh

Reputation: 2053

You can certainly do anything that you want with Reflection. but you should try and explore for other options too. Here is a a 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);
   }

}

Upvotes: 1

Related Questions