Another tricky issue with @NonNull fields is if you need two objects to have mutual @NonNull references to each other. Consider the following attempt where we want it to the case that each A object be associated with a specific B object, and that the B object contain a back-link to the A object:

Each class, A and B, declares a @NonNull field to refer to the other. A() creates a new B intance, passing it a reference to the new A object. Sadly, JSure refuses to assure this scenario:

Screen Shot 2015-09-30 at 3.19.26 PM.png (73.4 KiB) Viewed 1518 times

The problem is that within A() the reference 'this' is not considered a non-null reference. It is a partially initialized reference, and thus we cannot pass it to the @NonNull formal argument of constructor B(). We could attempt to fix this by changing the annotation on B() to be @Initialized(through="Object"). But this is unsatisfactory:

It doesn't actually capture the intent: B() is meant to hold on to a real @NonNull reference to an A object.

It just moves the problem into B(): the partially initialized argument cannot be assigned to a @NonNull field.

A field cannot be declared to be @Initalized, so we cannot continue to 'fix' the problem by replacing @NonNull with @Initialized.

The solution is to cast the reference to be @NonNull within A(). The analysis used to assure @NonNull uses the method Cast.toNonNull() to force a reference to be considered to be non-null. This is not a safe operation, and it's use is recorded specially in the verification results. Below we use a version of Cast.toNonNull() that takes a dummy String parameter that serves as a description of why the cast is necessary/safe:

public A() { bRef = new B(Cast.toNonNull(this, "B() only needs the reference and never dereferences it")); }}

@TrackPartiallyInitializedclass B { @NonNull private final A aRef;

B(final @NonNull A aRef) { this.aRef = aRef; }}

The two classes now assure in the manner we expect. Now we see that the chain of evidence for the actual parameter to the call B() includes the fact that the cast is the reason the reference is considered to be non-null. Because the cast is not safe, it is marked with a red dot, and every result that depends on the cast is poisoned with the red dot as well. Also note that the call to Cast.toNonNull() is recorded separately under the "Vouches" heading.