我不明白如何在注释处理器中检索Enum值。
我的注释是一个自定义Java验证注释:
@StringEnumeration(enumClass = UserCivility.class)
private String civility;在我的注释处理器上,我可以访问这些实例:
javax.lang.model.element.AnnotationValue
javax.lang.model.type.TypeMirror
javax.lang.model.element.TypeElement我知道它包含关于我的枚举的数据,因为我可以在调试模式中看到它。我也看到了ElementKind == Enum
但是我想知道所有的名字,谁能帮我。
编辑:我不能访问这个Enum的对象,因为我们是在一个注释处理器中,而不是在standart反射代码中。因此,我不能调用Class#getEnumConstants()或EnumSet.allOf(MyEnum.class),除非您告诉我如何从上面提到的类型中获取Class对象。
发布于 2013-05-13 09:44:50
我找到了一个解决方案(它使用了番石榴):
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();
}发布于 2020-06-11 16:46:27
Sebastian给出的答案是正确的,但是如果您使用的是Java 8或更高版本,您可以使用以下(更干净)的方法,而不是使用Google。
List<String> getEnumValues(TypeElement enumTypeElement) {
return enumTypeElement.getEnclosedElements().stream()
.filter(element -> element.getKind().equals(ElementKind.ENUM_CONSTANT))
.map(Object::toString)
.collect(Collectors.toList());
}发布于 2013-05-07 18:53:06
下面是一个完整的例子。注意在枚举值上使用getEnumConstants。
public class Annotate {
public enum MyValues {
One, Two, Three
};
@Retention(RetentionPolicy.RUNTIME)
public @interface StringEnumeration {
MyValues enumClass();
}
@StringEnumeration(enumClass = MyValues.Three)
public static String testString = "foo";
public static void main(String[] args) throws Exception {
Class<Annotate> a = Annotate.class;
Field f = a.getField("testString");
StringEnumeration se = f.getAnnotation(StringEnumeration.class);
if (se != null) {
System.out.println(se.enumClass());
for( Object o : se.enumClass().getClass().getEnumConstants() ) {
System.out.println(o);
}
}
}
}这将打印出来:
Three
One
Two
Threehttps://stackoverflow.com/questions/16424066
复制相似问题