Skip to content

Commit

Permalink
Report a warning for setters with boxed primitive types for primitive…
Browse files Browse the repository at this point in the history
… properties

RELNOTES=Report a diagnostic for setters with boxed primitive types for primitive properties
PiperOrigin-RevId: 659352853
  • Loading branch information
cushon authored and Google Java Core Libraries committed Aug 4, 2024
1 parent 812a797 commit 328a25c
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1626,7 +1626,7 @@ public static Builder builder() {

@AutoValue.Builder
public interface Builder {
Builder setAnInt(Integer x);
Builder setAnInt(int x);

Builder setANullableInteger(int x);

Expand All @@ -1646,12 +1646,6 @@ public void testPrimitiveAndBoxed() {

PrimitiveAndBoxed instance2 = instance1.toBuilder().setANullableInteger(5).build();
assertThat(instance2.aNullableInteger()).isEqualTo(5);

try {
instance1.toBuilder().setAnInt(null);
fail();
} catch (NullPointerException expected) {
}
}

@AutoValue
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,16 @@ private Optional<Copier> getSetterFunction(E propertyElement, ExecutableElement
return Optional.empty();
}
}
if (!parameterElement.asType().getKind().isPrimitive()
&& originalPropertyType(propertyElement).getKind().isPrimitive()) {
errorReporter
.reportWarning(
setter,
"[%sUnnecessaryBoxing] %s is primitive but parameter of setter method is not",
autoWhat(),
propertyString(propertyElement));
return Optional.empty();
}
return Optional.of(Copier.IDENTITY);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4008,6 +4008,36 @@ public void kotlinMetadataAnnotationsAreImplicitlyExcludedFromCopying() {
.doesNotContain("kotlin.Metadata");
}

@Test
public void autoValueBuilderNullableSetterPrimitiveGetter() {
JavaFileObject javaFileObject =
JavaFileObjects.forSourceLines(
"foo.bar.Baz",
"package foo.bar;",
"",
"import com.google.auto.value.AutoValue;",
"",
"@AutoValue",
"public abstract class Baz {",
" abstract int blam();",
"",
" @AutoValue.Builder",
" public interface Builder {",
" Builder blam(Integer x);",
" Baz build();",
" }",
"}");
Compilation compilation =
javac()
.withProcessors(new AutoValueProcessor(), new AutoValueBuilderProcessor())
.compile(javaFileObject);
assertThat(compilation)
.hadWarningContaining(
"property method foo.bar.Baz.blam() is primitive but parameter of setter method is not")
.inFile(javaFileObject)
.onLineContaining("Builder blam(Integer x)");
}

private static String sorted(String... imports) {
return stream(imports).sorted().collect(joining("\n"));
}
Expand Down

0 comments on commit 328a25c

Please sign in to comment.