Does @NullMarked make fields non-null? JSpecify in Java

A package-level annotation reaches fields through the language model's enclosure rules. That is the easy half; initialising the POJO and mapping entities is harder.

Binary Buddies · 5 min read · 2 views

You put @NullMarked on a package, drop a plain POJO into it with a private String data field, a setter and a getter, and then notice that new MyPojo() leaves data as null. If null-marking made the field non-null, the class breaks its own contract the moment it is constructed. That is the puzzle in this Stack Overflow question, and it comes up for anyone adopting JSpecify in a codebase with setter-initialised beans.

The question has two parts. The first is a semantics question: does a package-level annotation reach down to field types, or does it only cover method signatures? The second is a design question: if it does reach fields, can you null-mark a package full of objects that are populated after construction, such as JPA entities?

The answers below are short on the first part and more nuanced on the second. What follows works through both, and keeps clear which claims come from the JSpecify documentation and which are the answerers' judgement.

What @NullMarked actually says

The JSpecify Javadoc for @org.jspecify.annotations.NullMarked says the annotated element and the code transitively enclosed within it are in a null-marked context. In that context, type usages are generally considered to exclude null unless specified otherwise. The stated purpose is to avoid writing @NonNull many times throughout your code.

Nothing in that wording limits it to parameters and return types. It talks about type usages, and a field's declared type is a type usage like any other. The question's mental model, where the annotation is shorthand for @NonNull sprinkled everywhere, is a fair reading of the documentation, as the first answer confirms.

The enclosure chain from package to field

The word that matters is 'enclosed'. The Javadoc links it to javax.lang.model.element.Element::getEnclosedElements(), whose documentation says a class or interface encloses the fields, methods, constructors, record components and member classes and interfaces that it directly declares. A package encloses the top-level classes and interfaces within it. A module encloses the packages within it.

Chain those together and a field is enclosed by its declaring class, which is eventually enclosed by a top-level class, which is enclosed by its package. So a field is transitively enclosed by the package. The accepted answer's conclusion follows directly: if the package is @NullMarked, the field is implicitly non-null unless it is explicitly @Nullable, or a nearer enclosing element is @NullUnmarked.

Reading the POJO from the question

With that in mind, the expansion the asker wrote is correct in spirit. In a null-marked package, private String data, setData(String data) and String getData() all read as non-null types. The field is not ignored.

That does leave the default constructor as a real conflict. The class as written declares a non-null field and never initialises it, so the declared contract and the runtime state disagree from the first line of use. The annotation documents what the types mean; it is up to the tooling you run, and to you, to deal with a field that is null between construction and the first setter call. The accepted answer offers three ways to reconcile the two.

Option one: a nullable field behind a checked getter

If the property should never be null when someone reads it, you can model the gap honestly. The field is declared @Nullable, because it really can be null before initialisation, while the public surface stays non-null:

// Assuming package is @NullMarked
package com.example;

import java.util.Objects;
import org.jspecify.annotations.Nullable;

public class MyPojo {
    private @Nullable String data;

    public void setData(String data) {
        this.data = Objects.requireNonNull(data, "data");
    }

    public String getData() {
        return Objects.requireNonNull(data, "'data' not initialized yet");
    }
}

The answerer notes this is essentially what Kotlin's lateinit var compiles down to on the JVM. The cost is that a read before initialisation now fails loudly with a NullPointerException carrying a useful message, instead of leaking a null to a caller whose type says it cannot be there. The answerer also says plainly that they do not know how well this works with JPA or similar frameworks.

Option two: suppress the initialisation warning

If you use a checker such as NullAway, you can keep the field declared non-null and silence the complaint about it not being initialised with @SuppressWarnings("NullAway.Init"). The field then behaves like lateinit from the tool's point of view.

The trade-off is stated in the answer: it is now up to you to ensure the field is initialised before it is first queried. The checker has been told to stop verifying exactly the thing that was bothering you. This suits objects whose lifecycle you control tightly. It is a poor fit where several code paths can build the object and nothing guarantees every one of them calls the setter.

Option three: initialise to a non-null default

The third route removes the problem rather than modelling it. Give the field a real non-null starting value, such as "" for a String or an empty collection for collection types:

public class MyPojo {
    private String data = "";

    public void setData(String data) {
        this.data = Objects.requireNonNull(data, "data");
    }

    public String getData() {
        return data;
    }
}

Now new MyPojo() satisfies the contract and the getter needs no check. The price is that an empty string is a value, and callers can no longer tell 'never set' from 'set to empty'. For a collection, an empty default is usually exactly right. For an identifier or a required name, a silent "" can hide a bug that option one would have surfaced.

Why JPA entities are the hard case

The asker's real motivation was null-marking a package of JPA entities. The second answer calls that a bad idea, and argues from what an entity is: it represents a database row, not the thing itself. Take a Student entity whose unid column is filled from a sequence on insert. Until you call save(), the object is a potential row, and the Java side needs null to mean 'not set now, the database will fill it in', even if the column is NOT NULL. (Because a primitive int cannot hold null, that field would need to be a wrapper type in practice.)

The mapping also breaks in the other direction. A query can return rows shaped like your entity where a column is NULL despite a not-null constraint in the table definition, and the answer points to LEFT JOIN as the trivial case. Marking the field as truly never null on the Java side would then make such queries impossible, and the answer's view is that JPA is restrictive enough already. The alternative it describes is a mark that only means 'this column has a NOT NULL constraint', which is all JPA's own @NotNull promises.

Opting out with @NullUnmarked, and what a package does not cover

The Javadoc describes @NullMarked and @NullUnmarked as an inclusion-exclusion pair. Of the annotations of either type on all enclosing elements, only the nearest, most narrowly enclosing one is in effect. So you can keep a package null-marked and put @NullUnmarked on the entity classes, or on a single method, to return that code to the same state as unannotated code.

One boundary is easy to miss. A package encloses the top-level classes within it but is not considered to enclose subpackages. Annotating com.example does not mark com.example.entities; each package needs its own package-info.java. A module, by contrast, encloses its packages.

Where this does not fit

The answers do not settle everything, and it is worth being clear about the gaps. The accepted answer says it is not sure either way whether null-marking setter-initialised or reflection-initialised POJOs makes sense. It also says it does not know how the @Nullable-field pattern behaves with JPA. Neither answer tests a framework end to end, so treat both as informed opinion, not verified behaviour.

Practical limits follow from what they do say:

  • Objects populated by reflection or by a persistence layer will hold null in fields your types call non-null, and the annotation will not prevent that.
  • Suppressing the init warning moves the guarantee from the tool to your discipline.
  • Defaults like "" trade a loud failure for a quiet ambiguity.
  • For entities, null-marking the whole package declares a contract the persistence model cannot honour. Marking the domain and service packages while leaving entity packages unmarked, or explicitly @NullUnmarked, avoids that.

This article draws on Does @NullMarked package imply non-nullablity on a field level? and answers to it (1, 2), on the Stack Exchange network, licensed under CC BY-SA 4.0.

  • #JPA entities
  • #NullAway
  • #NullMarked
  • #NullUnmarked
  • #java
  • #jspecify

Comments

Add a comment
Sign in with Google to join the conversation