Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotation processor: get all enum values from a TypeMirror or TypeElement

I don't understand how I can retrieve the Enum values in an annotation processor.

My annotation is a custom Java Bean Validation annotation:

  @StringEnumeration(enumClass = UserCivility.class)
  private String civility;

On my annotation processor, I can access to instances of these:

javax.lang.model.element.AnnotationValue
javax.lang.model.type.TypeMirror
javax.lang.model.element.TypeElement

I know it contains the data about my enum since I can see that in debug mode. I also see ElementKind == Enum

But I want to get all the names for that Enum, can someone help me please.


Edit: I don't have access to the Class object of this Enum, because we are in an annotation processor, and not in standart Java reflection code. So I can't call Class#getEnumConstants() or EnumSet.allOf(MyEnum.class) unless you tell me how I can get the Class object from the types mentioned above.

like image 783
Sebastien Lorber Avatar asked May 07 '13 16:05

Sebastien Lorber


People also ask

Can you iterate through enums?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

Can enums be subclassed?

Yes. but in case each of the enums has all common attributes, The duplication in constructors and getters and setters is evident.

Are enums extendable?

Enums can be extended in order to add more values to the enumeration list in which case the Extensible property must be set to true .


1 Answers

I found a solution (this uses Guava):

class ElementKindPredicate<T extends Element> implements Predicate<T> {
    private final ElementKind kind;
    public ElementKindPredicate(ElementKind kind) {
      Preconditions.checkArgument(kind != null);
      this.kind = kind;
    }
    @Override
    public boolean apply(T input) {
      return input.getKind().equals(kind);
    }
}

private static final ElementKindPredicate ENUM_VALUE_PREDICATE = new ElementKindPredicate(ElementKind.ENUM_CONSTANT);

public static List<String> getEnumValues(TypeElement enumTypeElement) {
    Preconditions.checkArgument(enumTypeElement.getKind() == ElementKind.ENUM);
    return FluentIterable.from(enumTypeElement.getEnclosedElements())
        .filter(ENUM_VALUE_PREDICATE)
        .transform(Functions.toStringFunction())
        .toList();
}
like image 69
Sebastien Lorber Avatar answered Sep 22 '22 05:09

Sebastien Lorber