代码之家  ›  专栏  ›  技术社区  ›  Abbas

获取javax中VariableElement的封闭类名。注释。处理。加工机

  •  0
  • Abbas  · 技术社区  · 7 年前

    我刚刚开始学习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 注释并设置为封闭类,但我希望避免这种情况,因为它为第三方开发人员增加了额外的责任。

    0 回复  |  直到 7 年前
        1
  •  0
  •   Abbas    7 年前

    显然是个愚蠢的问题。我在所有错误的地方寻找封闭元素,发现这个非常棒 Annotation Processor Tutorial 其中规定:

    元素和类型镜像

    ...

    您可以将其视为试图解析的XML文件(或编译器构造中的抽象语法树)

    我意识到 Element 它本身可能包含我需要的所有信息。

    只需要打个电话 variableElement.getEnclosingElement() 为了得到父母 要素

    从那时起,很容易得到封闭的类名,如下所示:

    element.getEnclosingElement().asType().toString();
    

    然而,这并不能保证封闭元素是 TypeElement .所以只要使用 instanceof 确保它是正确的。