1

I have these annotations:

@interface NotNull {
  boolean value() default false;
}

@interface Type {
  Class<?> value();
}

and then I use them with an enum:

public enum KeyMap implements IMapEnum {

  @Type(Integer.class)
  @NotNull
  USER_ID("user_id", "userId"),

  @NotNull
  USER_HANDLE("user_handle", "userHandle"),

  @NotNull
  USER_EMAIL("user_email", "userEmail");

  private String key;
  private String value;

  KeyMap(String k, String v) {
    this.key = k;
    this.value = v;
  }

  @Override
  public String getKey() {
    return this.key;
  }

  @Override
  public String getValue() {
    return this.value;
  }

}

my question is - how do I retrieve the value of the annotation for each instance of the enum? The interface being implemented is simple and is not really part of the question:

public interface IMapEnum {
  String getKey();
  String getValue();
}

but maybe someone can show how to retrieve the annotations in either getKey or getValue method?

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111

1 Answers1

0

First you need to add runtime retention to your annotations so they can be read using reflection:

@Retention(RetentionPolicy.RUNTIME)
@interface NotNull {
    boolean value() default false;
}

@Retention(RetentionPolicy.RUNTIME)
@interface Type {
    Class<?> value();
}

Then you can use reflection to obtain the annotations treating enum constant as a class field:

Field field = KeyMap.class.getField(KeyMap.USER_ID.name());
Annotation[] annotations = field.getDeclaredAnnotations();
System.out.println(Arrays.toString(annotations));

will print:

[@Type(value=java.lang.Integer.class), @NotNull(value=false)]
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • Nice thanks a ton, will accept it tomorrow..quick question - how could I store the annotations in a map? Something like `Map.of(@Type, Integer.class, @NotNull, false)`...but how exactly? –  Feb 12 '19 at 11:14
  • @rakim apologies but I do not understand the `Map` question. You could create `Map` but I'm not sure if this is what you are looking for. – Karol Dowbecki Feb 12 '19 at 11:16
  • If I want to see if an object has a certain annotation? I could store the annotations in a map on the object, and then look up the annotation as a key in the map, right? –  Feb 13 '19 at 03:05
  • please see this question: https://stackoverflow.com/questions/54661961/store-annotations-in-a-map-and-look-them-up-later the reason is I only want to use reflection once, I don't want to keep using reflection look up the annotations everytime –  Feb 13 '19 at 03:16