我正在编写一个 OpenRewrite 配方来向 Java 代码添加一些注释。为了避免在不必要的地方插入注释,我编写了以下代码(它检测已经存在的注释)并且它工作正常:
public class JtestSuppressDelombokVisitor extends JavaIsoVisitor<ExecutionContext> {
@Override
public MethodDeclaration visitMethodDeclaration(MethodDeclaration methodDecl, ExecutionContext context) {
// (snip)
Iterator<Comment> it = methodDecl.getPrefix().getComments().iterator();
boolean alreadyHasSuppressComment = false;
while (it.hasNext()) {
Comment comment = it.next();
PrintOutputCapture<String> p = new PrintOutputCapture<String>("");
comment.printComment(this.getCursor(), p);
if (p.out.toString().matches(".*parasoft-begin-suppress\sALL.*")) {
alreadyHasSuppressComment = true;
break;
}
}
// (snip)
return methodDecl;
}
}
我尝试使用 Stream API 重构上面的代码。代码在此过程中需要
this.getCursor()
的结果,但我找不到将其传递给Predicate
实例的方法:
boolean alreadyHasSuppressComment = methodDecl.getPrefix().getComments().stream()
.anyMatch(new Predicate<Comment>() {
@Override
public boolean test(Comment comment) {
PrintOutputCapture<String> p = new PrintOutputCapture<String>("");
comment.printComment(this.getCursor(), p); // <- Can't call `this.getCursor()` on the `JtestSuppressDelombokVisitor` class in the `Predicate`
return p.out.toString().matches(".*parasoft-begin-suppress\sALL.*");
}
});
有什么办法可以将流上对象以外的对象从外部传递给
Predicate
吗?
或者说,用Stream API不可能写出这样的代码?
您需要指定外部类,因为唯一的
this
关键字引用实现的匿名 Predicate
类。
comment.printComment(JtestSuppressDelombokVisitor.this.getCursor(), p);