Annotation Type NullCheck


  • @Documented
    @Retention(SOURCE)
    @Target(TYPE)
    public @interface NullCheck
    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.

    Example usage:

     import groovy.transform.NullCheck
     import static groovy.test.GroovyAssert.shouldFail
    
     @NullCheck
     class Greeter {
         private String audience
    
         Greeter(String audience) {
             this.audience = audience.toLowerCase()
         }
    
         String greeting(String salutation) {
             salutation.toUpperCase() + ' ' + audience
         }
     }
    
     assert new Greeter('World').greeting('hello') == 'HELLO world'
    
     def ex = shouldFail(IllegalArgumentException) { new Greeter(null) }
     assert ex.message == 'audience cannot be null'
    
     ex = shouldFail(IllegalArgumentException) { new Greeter('Universe').greeting(null) }
     assert ex.message == 'salutation cannot be null'
     
    The produced code for the above example looks like this:
     class Greeter {
         private String audience
    
         Foo(String audience) {
             if (audience == null) throw new IllegalArgumentException('audience cannot be null')
             this.audience = audience.toLowerCase()
         }
    
         String greeting(String salutation) {
             if (salutation == null) throw new IllegalArgumentException('salutation cannot be null')
             salutation.toUpperCase() + ' ' + audience
         }
     }
     
    Since:
    3.0.0