Let's pretend that I hated null. Let's pretend that making it opt-out, like @Nullable, doesn't go far enough for me. Let's say I wanted it to be opt in; if an object is not explicitly annotated with @Nullable, then nulls are not allowed.
Example:
MyClass derp = null; // Compiler error
@Nullable MyClass derp = null; // Fine
@Nullable Integer x = 4; // Fine
@Nullable Integer x = null; // Fine
Integer x = 4; // Fine
Integer x = null; // Compiler error
Another example:
public static void myFunction(@Nullable Integer x) {
Integer y = x; // Compiler error, because we know x might
// be null, and that's not allowed. In other
// words: Integer != @Nullable Integer
}
How would I go about this? Would I write some sort of javac plugin? Perhaps a pre-compiler-pass? Maybe there's a framework out there that does this? Or perhaps I could modify the source code of javac?
Thanks!
Within code areas marked with @NonNullByDefault you basically get what the question asks for: any exception from that default needs to be explicitly declared. The default can be declared per class/interface or per package.
Note 1: You want the Java-8 variant of null annotations (null type annotations), so they affect type references in all positions.
Note 2: See the Java doc for details, where exactly the default applies (which can be fine tuned, btw).
ARRAY_CONTENTS
is intentionally omitted from this, due to difficulties like those mentioned in @Jon Skeet's comment.