我正在使用Elements.getElementValuesWithDefaults检索注释值。 返回的 Map 的键是扩展 ExecutableElement 的东西。我可以迭代 EntrySet 并检查每个键的名称,但这会导致丑陋的 if-else 级联。
Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues =
elementUtils.getElementValuesWithDefaults(annotationMirror);
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationValues.entrySet()) {
if (entry.getKey().getSimpleName().contentEquals("method1")) {
// do something with value of method1
} else if (entry.getKey().getSimpleName().contentEquals("method2")) {
// do something with value of method2
} else if (entry.getKey().getSimpleName().contentEquals("method3")) {
// do something with value of method3
}
}
我没有找到一种简单的方法来创建 ExecutableElement 作为获取值的键。有人知道吗?
最佳答案
您可以使用可运行映射。
Map<String, Runnable> map = new HashMap();
map.put("method1", new Runnable() { ... });
map.put("method2", new Runnable() { ... });
map.put("method3", new Runnable() { ... });
for (Map.Entry entry : ...) {
map.get(entry.getKey().getSimpleName()).run();
}
我猜您想将条目传递到方法中,因此您可能需要自定义接口(interface)而不是 Runnable。
关于java - AnnotationProcessing - 创建可执行元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21750913/