Annotation Interface Contract


@Documented @Retention(CLASS) @Target(METHOD) public @interface Contract
Inspired from org.jetbrains.annotations.Contract, this variant has been introduce in the org.springframework.lang package to avoid requiring an extra dependency, while still following the same semantics.

Specifies some aspects of the method behavior depending on the arguments. Can be used by tools for advanced data flow analysis. Note that this annotation just describes how the code works and doesn't add any functionality by means of code generation.

Method contract has the following syntax:
contract ::= (clause ';')* clause
clause ::= args '->' effect
args ::= ((arg ',')* arg )?
arg ::= value-constraint
value-constraint ::= 'any' | 'null' | '!null' | 'false' | 'true'
effect ::= value-constraint | 'fail' The constraints denote the following:

  • _ - any value
  • null - null value
  • !null - a value statically proved to be not-null
  • true - true boolean value
  • false - false boolean value
  • fail - the method throws an exception, if the arguments satisfy argument constraints

Examples: @Contract("_, null -> null") - method returns null if its second argument is null
@Contract("_, null -> null; _, !null -> !null") - method returns null if its second argument is null and not-null otherwise
@Contract("true -> fail") - a typical assertFalse method which throws an exception if true is passed to it

Since:
6.2
Author:
Sebastien Deleuze
See Also:
  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
    boolean
    Specifies if this method is pure, i.e.
    Contains the contract clauses describing causal relations between call arguments and the returned value.
  • Element Details

    • value

      String value
      Contains the contract clauses describing causal relations between call arguments and the returned value.
      Default:
      ""
    • pure

      boolean pure
      Specifies if this method is pure, i.e. has no visible side effects. This may be used for more precise data flow analysis, and to check that the method's return value is actually used in the call place.
      Default:
      false