Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import com.google.errorprone.VisitorState;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
Expand Down Expand Up @@ -301,7 +302,7 @@ public boolean onOverrideMayBeNullExpr(
if (isNullableFieldInLibraryModels(exprSymbol)) {
return true;
}
if (!(expr instanceof MethodInvocationTree
if (!(expr instanceof MethodInvocationTree invocation
&& exprSymbol instanceof Symbol.MethodSymbol methodSymbol)) {
return exprMayBeNull;
}
Expand All @@ -310,6 +311,11 @@ public boolean onOverrideMayBeNullExpr(
if (NullabilityUtil.isMapGetOrDefault(methodSymbol, state)) {
return true;
}

if (isCanonicalNameOfClassLiteral(invocation, methodSymbol, state)) {
return false;
}

OptimizedLibraryModels optLibraryModels = getOptLibraryModels(state.context);
// A model of a method's return nullness matches the exact signature when the method is
// annotated: the overriding method carries its own annotations, and an inherited model must
Expand Down Expand Up @@ -396,6 +402,10 @@ public NullnessHint onDataflowVisitMethodInvocation(
}
return anyNull ? NullnessHint.HINT_NULLABLE : NullnessHint.FORCE_NONNULL;
}

if (isCanonicalNameOfClassLiteral(castToNonNull(node.getTree()), callee, state)) {
return NullnessHint.FORCE_NONNULL;
}
if (optLibraryModels.hasNonNullReturn(callee, types, !isMethodAnnotated)) {
return NullnessHint.FORCE_NONNULL;
} else if (optLibraryModels.hasNullableReturn(callee, types, !isMethodAnnotated)) {
Expand Down Expand Up @@ -430,6 +440,40 @@ private boolean isNullableFieldInLibraryModels(@Nullable Symbol symbol) {
return false;
}

/**
* Checks whether {@code invocation} calls {@link Class#getCanonicalName()} directly on a class
* literal whose type has a canonical name, in which case the result is never {@code null}.
*
* <p>Per JLS 6.7, a class has no canonical name if it is local or anonymous, or if it is a member
* of a class without a canonical name; an array type has a canonical name iff its element type
* does. Anonymous classes have no class literal, so for a literal it suffices to check that the
* (element) type is not directly or indirectly local. Receivers that are not class literals, e.g.
* {@code clazz.getCanonicalName()} or {@code obj.getClass().getCanonicalName()}, never match.
*
* <p>No check on the owner of {@code callee} is needed: a class literal always has type {@code
* Class}, so the only {@code getCanonicalName} method it can invoke is {@code
* Class#getCanonicalName()}.
*
* @param invocation the method invocation to check
* @param callee the symbol of the invoked method
* @param state the visitor state
* @return true if the invocation is known to return a non-null value
*/
private static boolean isCanonicalNameOfClassLiteral(
MethodInvocationTree invocation, Symbol.MethodSymbol callee, VisitorState state) {
if (!callee.name.contentEquals("getCanonicalName")
|| !(ASTHelpers.getReceiver(invocation) instanceof MemberSelectTree literal)

@coderabbitai coderabbitai Bot Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Remove receiver parentheses before matching the class literal.

For (String.class).getCanonicalName().length(), ASTHelpers.getReceiver() preserves the parentheses. This check rejects the receiver, so the nullable warning remains. The pinned Error Prone implementation returns the selected expression unchanged. (raw.githubusercontent.com)

Strip parentheses before the MemberSelectTree check. Add positive coverage for (String.class) and negative coverage for (Local.class).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@msridhar apply this?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, why not, it's easy

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

|| !literal.getIdentifier().contentEquals("class")) {
return false;
}
Types types = state.getTypes();
Type type = castToNonNull(ASTHelpers.getType(literal.getExpression()));
while (types.isArray(type)) {
type = types.elemtype(type);
}
return !type.tsym.isDirectlyOrIndirectlyLocal();
}

private void setConditionalArgumentNullness(
AccessPathNullnessPropagation.Updates thenUpdates,
AccessPathNullnessPropagation.Updates elseUpdates,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,164 @@ public Optional<String> getNameOpt() {
.doTest();
}

@Test
public void getCanonicalNameOnClassLiteral() {
makeHelper()
.addSourceLines(
"Test.java",
"""
import java.util.Map;
import java.util.function.IntSupplier;
import org.jspecify.annotations.NullMarked;

@NullMarked
class Test {
static class Member {
static class MemberOfMember {}
}

Class<?> field = String.class;

static void takesNonNull(String s) {}

// ---- class literals of types with a canonical name: non-null ----

int topLevelClass() {
return String.class.getCanonicalName().length();
}

int memberClass() {
return Map.Entry.class.getCanonicalName().length();
}

int memberOfMemberClass() {
return Member.MemberOfMember.class.getCanonicalName().length();
}

int primitiveType() {
return int.class.getCanonicalName().length();
}

int voidType() {
return void.class.getCanonicalName().length();
}

int arrayOfTopLevelClass() {
return String[].class.getCanonicalName().length();
}

int arrayOfPrimitive() {
return int[][].class.getCanonicalName().length();
}

int viaLocalVariable() {
String name = String.class.getCanonicalName();
return name.length();
}

String returnedFromNonNullMethod() {
return String.class.getCanonicalName();
}

void passedAsNonNullArgument() {
takesNonNull(String.class.getCanonicalName());
}

// ---- class literals of types without a canonical name: nullable ----

int localClass() {
class Local {}
// BUG: Diagnostic contains: dereferenced expression 'Local.class.getCanonicalName()' is @Nullable
return Local.class.getCanonicalName().length();
}

int memberOfLocalClass() {
class Local {
class Inner {}
}
// BUG: Diagnostic contains: dereferenced expression 'Local.Inner.class.getCanonicalName()' is @Nullable
return Local.Inner.class.getCanonicalName().length();
}

int arrayOfLocalClass() {
class Local {}
// BUG: Diagnostic contains: dereferenced expression 'Local[].class.getCanonicalName()' is @Nullable
return Local[].class.getCanonicalName().length();
}

int localRecord() {
record LocalRecord() {}
// BUG: Diagnostic contains: dereferenced expression 'LocalRecord.class.getCanonicalName()' is @Nullable
return LocalRecord.class.getCanonicalName().length();
}

int localEnum() {
enum LocalEnum { A }
// BUG: Diagnostic contains: dereferenced expression 'LocalEnum.class.getCanonicalName()' is @Nullable
return LocalEnum.class.getCanonicalName().length();
}

int localInterface() {
interface LocalInterface {}
// BUG: Diagnostic contains: dereferenced expression 'LocalInterface.class.getCanonicalName()' is @Nullable
return LocalInterface.class.getCanonicalName().length();
}

int localClassInLambda() {
IntSupplier supplier = () -> {
class InLambda {}
// BUG: Diagnostic contains: dereferenced expression 'InLambda.class.getCanonicalName()' is @Nullable
return InLambda.class.getCanonicalName().length();
};
return supplier.getAsInt();
}

int localClassViaLocalVariable() {
class Local {}
String name = Local.class.getCanonicalName();
// BUG: Diagnostic contains: dereferenced expression 'name' is @Nullable
return name.length();
}

String localClassReturned() {
class Local {}
// BUG: Diagnostic contains: returning @Nullable expression from method with @NonNull return type
return Local.class.getCanonicalName();
}

void localClassPassedAsArgument() {
class Local {}
// BUG: Diagnostic contains: passing @Nullable parameter 'Local.class.getCanonicalName()' where @NonNull is required
takesNonNull(Local.class.getCanonicalName());
}

// ---- receivers that are not class literals: remain nullable ----

int classTypedParameter(Class<?> clazz) {
// BUG: Diagnostic contains: dereferenced expression 'clazz.getCanonicalName()' is @Nullable
return clazz.getCanonicalName().length();
}

int fieldReceiver() {
// BUG: Diagnostic contains: dereferenced expression 'this.field.getCanonicalName()' is @Nullable
return this.field.getCanonicalName().length();
}

int getClassReceiver(Object o) {
// BUG: Diagnostic contains: dereferenced expression 'o.getClass().getCanonicalName()' is @Nullable
return o.getClass().getCanonicalName().length();
}

int literalStoredInLocalVariable() {
Class<?> clazz = String.class;
// BUG: Diagnostic contains: dereferenced expression 'clazz.getCanonicalName()' is @Nullable
return clazz.getCanonicalName().length();
}
}
""")
.doTest();
}

private CompilationTestHelper makeHelper() {
return makeTestHelperWithArgs(
JSpecifyJavacConfig.withJSpecifyModeArgs(
Expand Down
Loading