Class NullnessCasts
- java.lang.Object
-
- com.google.common.collect.NullnessCasts
-
final class NullnessCasts extends java.lang.Object
A utility method to perform unchecked casts to suppress errors produced by nullness analyses.
-
-
Constructor Summary
Constructors Modifier Constructor Description private
NullnessCasts()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description (package private) static <T> T
uncheckedCastNullableTToT(T t)
Accepts aT
and returns a plainT
, without performing any check that that conversion is safe.(package private) static <T> T
unsafeNull()
Returnsnull
as any type, even one that does not includenull
.
-
-
-
Method Detail
-
uncheckedCastNullableTToT
static <T> T uncheckedCastNullableTToT(@CheckForNull T t)
Accepts aT
and returns a plainT
, without performing any check that that conversion is safe.This method is intended to help with usages of type parameters that have parametric nullness. If a type parameter instead ranges over only non-null types (or if the type is a non-variable type, like
String
), then code should almost never use this method, preferring instead to callrequireNonNull
so as to benefit from its runtime check.An example use case for this method is in implementing an
Iterator<T>
whosenext
field is lazily initialized. The type of that field would beT
, and the code would be responsible for populating a "real"T
(which might still be the valuenull
!) before returning it to callers. Depending on how the code is structured, a nullness analysis might not understand that the field has been populated. To avoid that problem without having to add@SuppressWarnings
, the code can call this method.Why not just add
SuppressWarnings
? The problem is that this method is typically useful forreturn
statements. That leaves the code with two options: Either add the suppression to the whole method (which turns off checking for a large section of code), or extract a variable, and put the suppression on that. However, a local variable typically doesn't work: Because nullness analyses typically infer the nullness of local variables, there's no way to assign aT
to a fieldT foo;
and instruct the analysis that that means "plainT
" rather than the inferred typeT
. (Even if supported added@NonNull
, that would not help, since the problem case addressed by this method is the case in whichT
has parametric nullness -- and thus its value may be legitimatelynull
.)
-
unsafeNull
static <T> T unsafeNull()
Returnsnull
as any type, even one that does not includenull
.
-
-