Enhancement: Add support for explicit receiver parameter validation.

Java 8 introduced explicit receiver parameters. It means that you can use this as the method argument and add additional annotation to it.

class Foo {
    private Integer x;

    //...

    public String validatedFoo(@Something Foo this) {
        return "validated " + x;
    }
}

In Spring you can add @Valid annotation to method argument to validate passing argument:

@Component
@Validated
class Foo {
    private Integer x;

    public Integer getX() {
        return x;
    }

    public void setX(@Valid @Min(0) Integer x) {
        this.x = x;
    }
//...
}

But this does not work for explicit receiver parameter. I would expect that validatedFoo() method could be called only on component in a valid state:

@Component
@Validated
class Foo {
    private Integer x;

    @Min(0)
    @NotNull
    public Integer getX() {
        return x;
    }

    //if method called on Foo instance with negative x, ConstraintViolationException should be thrown
    public String validatedFoo(@Valid Foo this) {
        return "validated " + x;
    }
}

Repository with test case: https://github.com/slawekludwiczak/explicit-receiver-parameter-spring

Comment From: simonbasle

Explicit receiver parameter in Java 8 is quite an interesting feature. Very obscure except for static checking implementers I guess :)

That said, we don't think this is something we'd like to pursue within Bean Validation. The goal of bean validation is to validate user input, eg. during construction or mutation of the object. This is not a replacement for asserting state of existing instances when operating on said instances.

It is also generally avoiding unnecessary re-validation once the input has been validated.

In the light of this, I'd advise you to use assertions. Spring Framework does offer some utilities for this btw, eg. in org.springframework.util.Assert.

If you have a pretty compelling case why you'd want to re-validate the instance on all invocations of a specific instance method, in a way that is not possible with programmatic assertions, feel free to ask us to re-open this issue.