Package org.springframework.lang
Annotation Interface Contract
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.
Inspired by org.jetbrains.annotations.Contract
, this variant has
been introduced in the org.springframework.lang
package to avoid
requiring an extra dependency, while still following the same semantics.
Method contract has the following syntax:
contract ::= (clause ';')* clause
clause ::= args '->' effect
args ::= ((arg ',')* arg )?
arg ::= value-constraint
value-constraint ::= '_' | 'null' | '!null' | 'false' | 'true'
effect ::= value-constraint | 'fail' | 'this' | 'new' | 'param<N>'
The constraints denote the following:
_
- any valuenull
- null value!null
- a value statically proved to be not-nulltrue
- true boolean valuefalse
- false boolean value
The additional return values denote the following:
fail
- the method throws an exception, if the arguments satisfy argument constraintsnew
- the method returns a non-null new object which is distinct from any other object existing in the heap prior to method execution. If method is also pure, then we can be sure that the new object is not stored to any field/array and will be lost if method return value is not used.this
- the method returns its qualifier value (not applicable for static methods)param1, param2, ...
- the method returns its first (second, ...) parameter value
Examples:
@Contract("_, null -> null")
- the method returns null if its second argument is null.@Contract("_, null -> null; _, !null -> !null")
- the method returns null if its second argument is null and not-null otherwise.@Contract("true -> fail")
- a typicalassertFalse
method which throws an exception iftrue
is passed to it.@Contract("_ -> this")
- the method always returns its qualifier (e.g.StringBuilder.append(String)
).@Contract("null -> fail; _ -> param1")
- the method throws an exception if the first argument is null, otherwise it returns the first argument (e.g.Objects.requireNonNull
).@Contract("!null, _ -> param1; null, !null -> param2; null, null -> fail")
- the method returns the first non-null argument, or throws an exception if both arguments are null (e.g.Objects.requireNonNullElse
).
- Since:
- 6.2
- Author:
- Sebastien Deleuze
- See Also:
-
Optional Element Summary
-
Element Details
-
value
String valueContains the contract clauses describing causal relations between call arguments and the returned value.- Default:
- ""
-