【问题标题】:Checking for absence of super class in annotation processor检查注释处理器中是否存在超类
【发布时间】:2011-10-12 09:48:32
【问题描述】:

当在注解处理器中获取TypeElement 时,您可以使用方法getSuperClass() 请求它的超类(或者更具体地说,它的TypeMirror)。 According to the JavaDoc,一个不明确扩展任何东西的类型(换句话说,Object 是超类)或者是一个接口将返回一个NoTypeNONE 作为TypeKind

忽略整个模型/镜像 API 似乎在每一个机会都会让您感到困惑的事实,我将如何可靠地检查这一点?以下是一些代码摘录:

//Cast is safe since TypeKind is checked before this
final TypeElement el = (TypeElement)annotatedElement;
...
final TypeMirror parent = el.getSuperclass();
//Checking whether "nothing" is extended
if(parent.getKind().equals(TypeKind.NONE) && parent instanceof NoType) {
    ...         
}

这是正确的方式吗?看起来比较笨重。由于equals method of TypeMirror 不应该用于语义相等性检查,我想知道将它用于TypeKind 是否安全。我的直觉是肯定的,因为它是一个枚举,但后来我对 instanceof 表示怀疑。

有没有更好的方法来做到这一点?整个 javax.lang.model 包及其子包在整个商店都有交叉引用,我永远不清楚什么是最好的方法。有些东西有有用的实用方法,然后有些看似简单的任务需要像上面这样可疑的杂技。

【问题讨论】:

    标签: java inheritance mirror annotation-processing


    【解决方案1】:

    我刚刚做了一个测试,发现我误解了文档。它为 java.lang.Object 和接口返回一个类型为 NONE 的 NoType,而不是为隐式扩展 Object 的东西。傻我。我不需要检查,因为前面检查了带注释的元素是否是严格意义上的类(不是枚举或接口),如果是则返回。换句话说,检查规范名称是 java.lang.Object 还是使用 Types.isSameType 应该可以解决问题。

    对不起各位。我决定不删除,因为其他人可能会遇到同样的问题。如果您认为合适,请随意投票删除。

    编辑:这就是我最终选择的……

    boolean superTypeValid = true;
    final TypeMirror parent = el.getSuperClass();
    if(!parent.getKind().equals(TypeKind.DECLARED)) {
        messager.printMessage(Kind.ERROR, "May only inherit from a class; not enums, annotations or other declared kinds.", annotatedElement, mirror);
        superTypeValid = false;
    } else {
        final DeclaredType parentType = (DeclaredType)parent;
        final Element parentEl = parentType.asElement();
        if(!parentEl.getKind().equals(ElementKind.CLASS)) {
            messager.printMessage(Kind.ERROR, "May only inherit from a class; not enums, annotations or other declared kinds.", annotatedElement, mirror);
            superTypeValid = false;
        }
    }
    ...
    if(superTypeValid) {
        if(typeUtils.isSameType(parent, elUtils.getTypeElement("java.lang.Object").asType())) {
            messager.printMessage(Kind.ERROR, "Inherit must not be set to true if the class doesn't extend.", annotatedElement, mirror);
            valid = false;
        } else {
            ...
        }
    }
    

    如果其中一些错误消息看起来很奇怪,那是因为我遗漏了一些特定于项目的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多