Skip to content

Commit c5519e7

Browse files
SONARJAVA-5340 FP on S1171 in anonymous classes (#5411)
1 parent 086763e commit c5519e7

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

java-checks-test-sources/default/src/main/java/checks/NonStaticClassInitializerCheckSample.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@ class NonStaticClassInitializerCheckSample {
44
static {
55
}
66

7+
static class Inner {
8+
{ // Noncompliant
9+
}
10+
}
11+
712
{ // Noncompliant {{Move the contents of this initializer to a standard constructor or to field initializers.}}
813
//^
914
System.out.println();
@@ -14,7 +19,7 @@ public NonStaticClassInitializerCheckSample() {
1419

1520
new Runnable() {
1621

17-
{ // Noncompliant
22+
{
1823
System.out.println();
1924
}
2025

java-checks/src/main/java/org/sonar/java/checks/NonStaticClassInitializerCheck.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,13 @@ public List<Tree.Kind> nodesToVisit() {
3434

3535
@Override
3636
public void visitNode(Tree tree) {
37-
reportIssue(((BlockTree) tree).openBraceToken(), "Move the contents of this initializer to a standard constructor or to field initializers.");
37+
if (!isMemberOfAnonymousClass(tree)) {
38+
reportIssue(((BlockTree) tree).openBraceToken(), "Move the contents of this initializer to a standard constructor or to field initializers.");
39+
}
40+
}
41+
42+
private static boolean isMemberOfAnonymousClass(Tree tree) {
43+
Tree parent = tree.parent();
44+
return parent.is(Tree.Kind.CLASS) && parent.parent() != null && parent.parent().is(Tree.Kind.NEW_CLASS);
3845
}
3946
}

0 commit comments

Comments
 (0)