在注解处理器中获取 a时,您可以使用 methodTypeElement
请求它的超类(或更具体地说,它的超类) 。根据 JavaDoc,不明确扩展任何东西的类型(换句话说,是超类)或接口将返回 a with as 。TypeMirror
getSuperClass()
Object
NoType
NONE
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
TypeMirror 的方法不应该用于语义相等检查,我想知道将它用于TypeKind
. 我的直觉说是的,因为它是一个枚举,但是我对此表示怀疑instanceof
。
有没有更好的方法来做到这一点?整个 javax.lang.model 包及其子包在整个商店都有交叉引用,我从来没有真正清楚什么是最好的方法。有些东西有有用的实用方法,然后有些看似简单的任务需要像上面这样可疑的杂技。