Repository navigation
Description
(This bug report was generated by Claude Sonnet 5.5 with "high" effort. See also PicnicSupermarket/error-prone-support#2299 (comment).)
The JSpecify JDK model correctly declares Class#getCanonicalName() as @Nullable-returning, as local and anonymous classes have no canonical name (JLS 6.7). For an invocation whose receiver is a class literal the answer is statically known, so a specialized handler could treat it as @NonNull, avoiding Objects.requireNonNull(...) noise on idioms such as String.class.getCanonicalName().
Care is needed, as a class literal can denote a class without a canonical name. On JDK 25:
| Class literal | getCanonicalName() |
|---|---|
String.class, Map.Entry.class, a member of a member, int.class, void.class, String[].class |
non-null |
Local.class (local class, record, enum or interface) |
null |
Local.Inner.class (member of a local class) |
null |
Local[].class (array of a local class) |
null |
So the result is non-null iff the (array element) type of the literal is not isDirectlyOrIndirectlyLocal(). Anonymous classes have no class literal. Invocations on non-literal receivers (clazz.getCanonicalName(), object.getClass().getCanonicalName()) must remain @Nullable.
import org.jspecify.annotations.NullMarked;
@NullMarked
class Repro5 {
int topLevel() {
return String.class.getCanonicalName().length(); // Desired: no warning.
}
int local() {
class Local {}
return Local.class.getCanonicalName().length(); // Must still warn.
}
}Options: -XepOpt:NullAway:OnlyNullMarked=true -XepOpt:NullAway:JSpecifyMode=true -XepOpt:NullAway:JSpecifyExperimental=true
Repro5.java:6: warning: [NullAway] dereferenced expression 'String.class.getCanonicalName()' is @Nullable
return String.class.getCanonicalName().length(); // Desired: no warning.
^
Repro5.java:11: warning: [NullAway] dereferenced expression 'Local.class.getCanonicalName()' is @Nullable
return Local.class.getCanonicalName().length(); // Must still warn.
^
Motivation: Class#getCanonicalName is the idiom some code bases prescribe over hard-coded type names (for refactoring safety), so wrapping it is not an option there; the documented alternative is -XepOpt:NullAway:IgnoreLibraryModelsFor=java.lang.Class.getCanonicalName, which also discards the @Nullable for the cases above that do return null.
Activity
Make NullAway happier with Guava.
Make NullAway happier with Guava.
vitinh0z commentedon Nov 25, 2026
Hi! I'd like to take this one. I'll put together a PR with a handler that treats
Class#getCanonicalName()as@NonNullwhen the receiver is a class literal whose (array element) type is not directly or indirectly local, keeping it@Nullablefor local classes and non-literal receivers, with tests for the cases in the table above.msridhar commentedon Nov 25, 2026
Not sure we need a separate handler for this. I might try just adding some extra logic to
LibraryModelsHandlerand see how that looks first.Treat Class#getCanonicalName() on class literals as non-null