Getting Started with Annotation ContractsAnnotation Contracts is one of the new features of GContracts 1.2 . The main principle behind is to reuse small but reoccurring parts of pre- and post-condition expressions. This article is about creating a simple
@NotNullcan be applied on method parameters in order to automatically add null checks to the method's precondition.
Let's Get StartedThe first step when creating an annotation contract is to create a custom annotation, in this case
@NotNull. Depending on whether the expression should be part of the pre- or post-condition, the author needs to specify
org.gcontracts.annotations.metapackage). The expression which is supposed to be added to the precondition is specified with the
@AnnotationContractannotation has a single annotation closure which has to hold a boolean expression. The value of the parameter can be referenced with
@Retentionand @Target are optional. GContracts will inject those meta-annotations if not available in the annotation contract definition. Currently, only
How to Apply the Annotation ContractApplying the annotation contracts is pretty straight-forward. Just add it to the appropriate parameter(s): During the compilation process GContracts will inject a newly created precondition for method
doSomethingthat will check parameter
param. With a precondition already specified, the null check will be merged into the existing boolean expression by conjunction.