Starting from Groovy 3.0.2, the @NullCheck annotation offers includeGenerated option. This option allows to use the annotation in combination with other AST transformations like @Immutable or @TupleConstructor .

import groovy.transform.CompileStatic import groovy.transform.Immutable import groovy.transform.NullCheck @CompileStatic @NullCheck(includeGenerated = true) @Immutable class Foo { final String str String bar(final BigDecimal value) { return str.toUpperCase() + " = " + value.toString() } } assert new Foo("test").bar(BigDecimal.TEN) == "TEST = 10" new Foo(null).bar(BigDecimal.ONE)

Output:

$ groovy test.groovy Caught: java.lang.IllegalArgumentException: args cannot be null java.lang.IllegalArgumentException: args cannot be null at Foo.<init>(test.groovy) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at test.run(test.groovy:18) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

If we skip setting includeGenerated to true, the @NullCheck annotation won’t be applied and we will see NullPointerException instead of the IllegalArgumentException .

$ groovy test.groovy Caught: java.lang.NullPointerException java.lang.NullPointerException at Foo.bar(test.groovy:12) at Foo$bar.call(Unknown Source) at test.run(test.groovy:18) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

Groovy Tutorial | Avoiding NPE with @NullCheck annotation | #groovylang @NullCheck is class, method, or constructor annotation which indicates that each parameter should be checked to ensure it isn't null. If placed at the class level, all explicit methods and constructors will be checked. This feature was added in Groovy 3.0 Watch now 4:20

Thank you!

Thank you so much for reading up to this point! I hope this article met your expectations, and you have learned something valuable from it. If you have one more minute, leave me a comment below, please. This way, I can thank you for your time more in person.

And last but not least. If you find this blog post valuable, help me spread the word, please. You can share it on Twitter, LinkedIn, or anywhere else you can think of. This single tweet or post on social media helps a lot. One more time - thank you so much! You’re awesome!