我尝试使用 java 注释处理器并尝试了解“javax.lang.model”中类的用法。对于我所阅读的内容,我认为 ElementVisitor 旨在作为使用模型的主要方式。但我不明白如何正确使用它。
我知道访客模式。到目前为止,我已经使用它来避免迭代元素的子元素(以及子元素的子元素......)并避免丑陋的“instanceof”测试。但这访客似乎不一样。如果我在模型元素上调用“接受”,它不会访问子元素,而只会访问元素本身。
有人可以提供有关如何使用 API 的帮助吗?
我找到了以下链接:http : //www.cs.bgu.ac.il/~gwiener/programming/visitors-galore/#more-113。但是在另一个内部使用一个访问者......只是感觉不对!?
编辑:为了更容易理解这个问题,我从上面的链接中复制了代码。以下代码似乎不“正确”。我不敢相信官方的 java API 是这样设计的。但是如何正确使用 ElementVisitor 呢?
tElem.accept(new SimpleElementVisitor6<Void, ...>() {
public Void visitType(TypeElement e, ...) {
for (Element tSubElem : e.getEnclosedElements()) {
tSubElem.accept(new SimpleElementVisitor6<AssocEndSpec, ...>() {
public AssocEndSpec visitExecutable(ExecutableElement ex, ...) {
TypeMirror tRetTypeMirror = ex.getReturnType();
tRetTypeMirror.accept(new SimpleTypeVisitor6<TypeElement, TypeElement>() {
public TypeElement visitDeclared(DeclaredType t, TypeElement enclose) {
for (TypeMirror tTypeArgMirror : t.getTypeArguments()) {
tTypeArgMirror.accept(new SimpleTypeVisitor6<TypeElement, ...>() {
public TypeElement visitDeclared(DeclaredType t, TypeElement self) {
TypeElement tArgTypeElem = (TypeElement) t.asElement();
if (!self.equals(tArgTypeElem)) {
// found the little bugger!
}
}
}, ...);
}
}
}, ...);
}
}, ...);
}
}, ...);
Run Code Online (Sandbox Code Playgroud)
这段代码是胡说八道。
看看javax.lang.model.util.ElementKindVisitor6或者javax.lang.model.util.ElementScanner6,他们可能会做什么。无论如何,您应该能够获取他们的资源并根据您的需求进行调整。
注意:话虽这么说,是的,我也想说 ElementVisitor 是访问者的一个相当奇怪的实现。
| 归档时间: |
|
| 查看次数: |
2546 次 |
| 最近记录: |