Pass the object other than the object on the stream to Predicate

115 Views Asked by At

Background

I am writing an OpenRewrite recipe to add some comments to the Java code. To avoid inserting the comment at unnecessary points, I have written the following code (it detects the already existing comment) and it worked properly:

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;
    }
}

Problem

I have tried to refactor the code above with the Stream API. The code needs the result of this.getCursor() in the process, but I couldn't find the way to pass it to the instance of 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.*");
            }
        });

Question

Is there any way to pass the object other than the object on the stream from outside to Predicate? Or, it is impossible to write such a code with the Stream API?

1

There are 1 best solutions below

1
On

You need to specify the outer class because the sole this keyword refers to the implemented anonymous Predicate class.

comment.printComment(JtestSuppressDelombokVisitor.this.getCursor(), p);