我刚刚开始学习Java中的注释处理。我有
@MyAnnotation
哪些目标
ElementType.FIELD
,在我的
Processor
我将注释限制为只允许非null unique
value
.这是正常的。
在记录错误时,如果实际上存在一些重复
价值
开始
MyAnnotation.value
,我想提供源代码中现有注释和新的重复注释的完整路径。
我的注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
public @interface ProviderColumn {
String content_id();
}
示例父类。
public class EnclosingParent {
@ProviderColumn(content_id="Hello")
private String value1;
@ProviderColumn(content_id="Hello")
private String value2;
}
我的注释处理器
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment)
{
UniqueColumnNameChecker columnNameChecker = new UniqueColumnNameChecker();
try {
for (Element annotatedElement : roundEnvironment.getElementsAnnotatedWith(ProviderColumn.class)) {
// We can cast it, because we know that it is of ElementType.FIELD
VariableElement variableElement = (VariableElement) annotatedElement;
try {
ProviderColumnId providerColumnId =
new ProviderColumnId(variableElement);
// How can I get the EnclosingParent.class or even just a complete canonical class name?
// throws a DuplicateAnnotationIdException when it detects duplicate entries.
columnNameChecker.addAnnotationColumnName(providerColumnId);
}
catch (IllegalArgumentException e) {
error(variableElement, e.getMessage());
return true;
}
}
}
catch (DuplicateAnnotationIdException ex) {
error(ex.getMessage());
return true;
}
return true;
}
然而,我很难弄清楚如何从一个
VariableElement
.因为我才刚开始
AnnotationProcessing
我甚至不确定这是否可行,我还没有在StackOverflow或其他任何地方找到任何与此问题相关的问题。
预期错误输出
Duplicate content_id()='Hello' detected, Found at 'com.example.EnclosingParent.value1' and 'com.example.EnclosingParent.value2'.
注意:我意识到如果我定义一个新的
ElementType.TYPE
注释并设置为封闭类,但我希望避免这种情况,因为它为第三方开发人员增加了额外的责任。