JSR 305 proposes adding anotations for defect detections, One enhancements proposed in this JSR is a null check annotation, Find Bugs and IntelliJ already provides support for this. When you use the @NotNull annotation you are defining that your code will not except a null parameter, if you were to provide a null parameter, the annotation would throw a RuntimeException. IntelliJ has integrated its use into the IDE, hence at compile time you you can be warned when you are about to assign NULL to a field that has been annotated as @NotNull.
The argument against using anotiations is that they should not to be used for language features. Also using the @NotNull annotation does reduce code clarity. Personally, once I got used to reading code littered with annotations, I did not find this an issue.
Example method using the @NotNull annotation.
public void MyMethodNotExceptingNull(@NotNull String param) { param.length() }
because your method is defined not to accept null, you no longer have to provide boiler plate code to check for it :
if (param != null) param.length()
you can also define fields and local varibles to be @NotNull :
@NotNull String myString;
Not only can you define @NotNull in your class methods but also in your interface methods.
Note : JSR305 attempts to standardize the name of the annotation currently findbugs calls it @NonNull and intelij calls it @NotNull
more details on findbug support for @NonNull
Example Annotation Code
The implementation of the @NotNull annotation looks like this.
import core.validation.ConstraintValidator; import core.validation.NotNullConstraint; import java.lang.annotation.*; /** * An element annotated with NutNull claims <code>null</code> value is <em>forbidden</em> * to return (for methods), pass to (parameters) and hold (local variables and fields). * Apart from documentation purposes this annotation is intended to be used by static analysis tools * to validate against probable runtime errors and element contract violations. * * @author max */ @Documented @ConstraintValidator(NotNullConstraint.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE}) public @interface NotNull { /** * @return unknown */ String value() default ""; /** * @return the message if this field is null. */ String message() default "must not be null."; }