Skip to content

Commit 87c5ef3

Browse files
S2325 Do not report on instance main.
1 parent 6bb2693 commit 87c5ef3

4 files changed

Lines changed: 34 additions & 1 deletion

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
void main() {
2+
System.out.println("Hello, World!");
3+
}

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,3 +426,20 @@ private List<List<T>> requiresNestedTypeVar() { // Compliant
426426
}
427427
}
428428
}
429+
430+
// Note `final` on the class indicating that main methods will not be overridden.
431+
// Without it, the check would apply only to private methods.
432+
final public class StaticMethodCheckSample {
433+
void main() { // Compliant
434+
System.out.println("StaticMethodCheckSample no arg main");
435+
}
436+
437+
void main(String[] args) { // Compliant
438+
System.out.println("StaticMethodCheckSample main with args");
439+
}
440+
441+
// Intentional FN to keep things simple.
442+
void main(int i) { // Compliant
443+
System.out.println("i = " + i);
444+
}
445+
}

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,13 +160,18 @@ private static boolean shouldBePlacedAfterStatic(Modifier modifier) {
160160
}
161161

162162
private static boolean isExcluded(MethodTree tree) {
163-
return tree.is(Tree.Kind.CONSTRUCTOR) || EXCLUDED_SERIALIZABLE_METHODS.matches(tree) || hasEmptyBody(tree);
163+
return tree.is(Tree.Kind.CONSTRUCTOR) || EXCLUDED_SERIALIZABLE_METHODS.matches(tree) || hasEmptyBody(tree) || isInstanceMain(tree);
164164
}
165165

166166
private static boolean hasEmptyBody(MethodTree tree) {
167167
return tree.block() != null && tree.block().body().isEmpty();
168168
}
169169

170+
private static boolean isInstanceMain(MethodTree tree) {
171+
// For simplicity check only the name.
172+
return "main".equals(tree.simpleName().toString());
173+
}
174+
170175
@Override
171176
public void visitIdentifier(IdentifierTree tree) {
172177
super.visitIdentifier(tree);

java-checks/src/test/java/org/sonar/java/checks/StaticMethodCheckTest.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,14 @@ void test() {
3232
.verifyIssues();
3333
}
3434

35+
@Test
36+
void test_compact_source() {
37+
CheckVerifier.newVerifier()
38+
.onFile(mainCodeSourcesPath("checks/StaticMethodCheckCompactSample.java"))
39+
.withCheck(new StaticMethodCheck())
40+
.verifyNoIssues();
41+
}
42+
3543
@Test
3644
void test_non_compiling() {
3745
CheckVerifier.newVerifier()

0 commit comments

Comments
 (0)