I want to inject non-null values into my groovy class
class MyClass {
private final String foo
private final Integer bar
MyClass(String foo, Integer bar) {
// wanted ctr body
}
...
}
Within the constructor, I want to assign the params to the respective fields AND prevent null values.
I wonder if there is a groovier way of doing this than the quite verbose
assert foo != null
assert bar != null
this.foo = foo
this.bar = bar
or
this.foo = Objects.requireNonNull foo
this.bar = Objects.requireNonNull bar
If you use Groovy 3, you can use @NullCheck
annotation that adds defensive conditions constructor (or any methods) arguments.
import groovy.transform.NullCheck
@NullCheck
class MyClass {
private final String foo
private final Integer bar
MyClass(String foo, Integer bar) {
this.foo = foo
this.bar = bar
}
}
// Examples:
new MyClass("test", null) // throws IllegalArgumentException("bar cannot be null")
new MyClass(null, "test") // throws IllegalArgumentException("foo cannot be null")
When you add @NullCheck
on the class definition level, defensive null-check will be applied to all constructors and methods. Alternatively, you can add @NullCheck
annotation to the methods (or constructors) you want to use this null-check only.
Before Groovy 3 such defensive checks have to be implemented manually.
Only an important nuance, because the @NullCheck annotation only apply to explicit methods and constructos, as it is indicated in the official documentation.
http://docs.groovy-lang.org/next/html/gapi/groovy/transform/NullCheck.html
If placed at the class level, all explicit methods and constructors will be checked.
If you are using other annotations as @TupleConstructor, all the implicit methods and constructors are not going to check parameters are not null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With