微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 检查注释处理器中是否缺少超类

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

无视整个模型/镜像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是否安全.我的直觉是肯定的,因为它是一个枚举,但后来我对这种情况产生怀疑.

有没有更好的方法呢?整个javax.lang.model包及其子代在整个商店都有交叉引用,我从来都不清楚什么是最好的方法.对于某些东西有一些有用的实用方法,然后看似简单的任务需要如上所述的可疑杂技.

解决方法

我刚做了一个测试,发现我误解了文档.它为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,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.",mirror);
        valid = false;
    } else {
        ...
    }
}

如果其中一些错误消息看起来很奇怪,那是因为我留下了一些项目特定的东西.

原文地址:https://www.jb51.cc/java/239782.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐