From da203f41d017bcb6b45bcebdb36cad3ab565c92a Mon Sep 17 00:00:00 2001 From: Bartek Pacia Date: Tue, 8 Jul 2025 17:01:11 +0200 Subject: [PATCH] [java-inspections] IDEA-374865 ClassCanBeRecord: fix `this` not being considered a reference to containing class In response to IJ-CR-167896 GitOrigin-RevId: e1046f37f326ea127d14d27d332001800e46d327 --- .../ConstructorBodyProcessor.java | 6 ++++++ .../beforeDelegating_6.java | 15 +++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 java/java-tests/testData/inspection/classCanBeRecord/flexibleConstructorBodies/beforeDelegating_6.java diff --git a/java/java-impl-inspections/src/com/intellij/codeInspection/classCanBeRecord/ConstructorBodyProcessor.java b/java/java-impl-inspections/src/com/intellij/codeInspection/classCanBeRecord/ConstructorBodyProcessor.java index 170413c01234..6a9bdfffe360 100644 --- a/java/java-impl-inspections/src/com/intellij/codeInspection/classCanBeRecord/ConstructorBodyProcessor.java +++ b/java/java-impl-inspections/src/com/intellij/codeInspection/classCanBeRecord/ConstructorBodyProcessor.java @@ -252,6 +252,12 @@ final class ConstructorBodyProcessor { if (expression == null) return false; Ref hasReferenceToClassUnderConstruction = new Ref<>(false); expression.accept(new JavaRecursiveElementWalkingVisitor() { + @Override + public void visitThisExpression(PsiThisExpression expression) { + super.visitThisExpression(expression); + hasReferenceToClassUnderConstruction.set(true); + } + @Override public void visitReferenceExpression(PsiReferenceExpression expression) { super.visitReferenceExpression(expression); diff --git a/java/java-tests/testData/inspection/classCanBeRecord/flexibleConstructorBodies/beforeDelegating_6.java b/java/java-tests/testData/inspection/classCanBeRecord/flexibleConstructorBodies/beforeDelegating_6.java new file mode 100644 index 000000000000..1ec56f6faabe --- /dev/null +++ b/java/java-tests/testData/inspection/classCanBeRecord/flexibleConstructorBodies/beforeDelegating_6.java @@ -0,0 +1,15 @@ +// "Convert to record class" "false" +class Person { + final String name; + final int age; + + Person(String name, int age) { + this.name = name; + this.age = age; + } + + Person(Person person) { + System.out.println(this); // javac error: "cannot reference this before supertype constructor has been called" + this(person.name, person.age); + } +} \ No newline at end of file