checkers.nullness
Class CollectionToArrayHeuristics
java.lang.Object
checkers.nullness.CollectionToArrayHeuristics
public class CollectionToArrayHeuristics
extends Object
Handles calls to Collection.toArray()
and determines
the appropriate nullness type of the returned value.
Collection.toArray()
and Collection.toArray(T[])
method semantics cannot be captured by the
regular type system. Namely, the nullness of the returned array
component depends on the receiver type argument. So
Collection<@NonNull String> c1 = ...
c1.toArray(); // --> returns @NonNull Object []
Collection<@Nullable String> c2 = ...
c2.toArray(); // --> returns @Nullable Object []
In the case of Collection.toArray(T[])
, the type of the returned array depends on the
passed parameter as well and its size. In particular, the returned
array component would of type @NonNull
if the following
conditions hold:
- The receiver collection type argument is
NonNull
- The passed array size is less than the collection size
While checking for the second condition, requires a runtime check, we
provide heuristics to handle the most common cases of Collection.toArray(T[])
, namely if the
passed array is
- an empty array initializer, e.g.
c.toArray(new String[] { })
,
- array creation tree of size 0, e.g.
c.toArray(new String[0])
, or
- array creation tree of the collection size method invocation
c.toArray(new String[c.size()])
Note: The nullness of the returned array doesn't depend on the passed
array nullness.
Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
CollectionToArrayHeuristics
public CollectionToArrayHeuristics(ProcessingEnvironment env,
NullnessAnnotatedTypeFactory factory)
handle
public void handle(MethodInvocationTree tree,
AnnotatedTypeMirror.AnnotatedExecutableType method)
- Apply the heuristics to the given method invocation and corresponding
Collection.toArray()
type.
If the method invocation is a call to toArray
, then it
manipulates the returned type of method
arg to contain the
appropriate nullness. Otherwise, it does nothing.
- Parameters:
tree
- method invocation treemethod
- invoked method type