jspecify View article history Edit article

Published: , Updated:
Talks about: <a class="post-tag post-tag-java" href="/tags/java">java</a>, <a class="post-tag post-tag-jspecify" href="/tags/jspecify">jspecify</a>, and <a class="post-tag post-tag-nullness" href="/tags/nullness">nullness</a>

Every Java developer has probably encountered a NullPointerException at least once in their life. The exception is thrown every time you try to dereference and use some object before initializing it. The following snippet shows a simple example:

String someName;         // value is 'null'

someName.toUpperCase(); // throws NullPointerException

Modern IDEs have some sort of detection for this kind of problem and warn developers while they are writing code like this. Those IDEs typically rely on static code analysis to determine if a value is null and therefore a potential for a NullPointerException is present in your code. To improve the result of such an analysis, annotations can be placed on your code which signal that a parameter can or can not be null. Multiple approaches have existed in the past to define a standard set of annotations for such a task, however none of them succeeded.

jspecify is the latest approach that tries to establish a standard. It has gained wide community support and recently celebrated their first public release (0.3.0).

The following snippet shows the dependency declaration for Maven projects:

<dependencies>
    <dependency>
        <groupId>org.jspecify</groupId>
        <artifactId>jspecify</artifactId>
        <version>0.3.0</version>
    </dependency>
</dependencies>

In case you want to declare that nothing in your module can ever be null, place the @NullMarked on your module-info.java like this:

@org.jspecify.annotations.NullMarked
module your.module.here {

    requires org.jspecify;

    // ...

}

The tooling support is not quiet clear yet, however if you are developing a library there is no harm in adding these annotations now and let your users enjoy their null-free life once tools have caught up.