Skip to content
Merged
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
@@ -0,0 +1,3 @@
void main() {
System.out.println("Hello, World!");
}
Original file line number Diff line number Diff line change
Expand Up @@ -426,3 +426,19 @@ private List<List<T>> requiresNestedTypeVar() { // Compliant
}
}
}

// Note `final` on the class indicating that main methods will not be overridden.
// Without it, the check would apply only to private methods.
final public class StaticMethodCheckSample {
void main() { // Compliant
System.out.println("StaticMethodCheckSample no arg main");
}

void main(String[] args) { // Compliant
System.out.println("StaticMethodCheckSample main with args");
}

void main(int i) { // Noncompliant
System.out.println("i = " + i);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ public class StaticMethodCheck extends BaseTreeVisitor implements JavaFileScanne
.addWithoutParametersMatcher()
.build());

private static final MethodMatchers MAIN_METHOD =
MethodMatchers.create()
.ofAnyType()
.names("main")
.addParametersMatcher(params ->
params.isEmpty() || (params.size() == 1 && params.get(0).isSubtypeOf("java.lang.String[]")))
.build();

private JavaFileScannerContext context;
private Deque<MethodReference> methodReferences = new LinkedList<>();

Expand Down Expand Up @@ -160,7 +168,7 @@ private static boolean shouldBePlacedAfterStatic(Modifier modifier) {
}

private static boolean isExcluded(MethodTree tree) {
return tree.is(Tree.Kind.CONSTRUCTOR) || EXCLUDED_SERIALIZABLE_METHODS.matches(tree) || hasEmptyBody(tree);
return tree.is(Tree.Kind.CONSTRUCTOR) || EXCLUDED_SERIALIZABLE_METHODS.matches(tree) || hasEmptyBody(tree) || MAIN_METHOD.matches(tree);
}

private static boolean hasEmptyBody(MethodTree tree) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ void test() {
.verifyIssues();
}

@Test
void test_compact_source() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/StaticMethodCheckCompactSample.java"))
.withCheck(new StaticMethodCheck())
.verifyNoIssues();
}

@Test
void test_non_compiling() {
CheckVerifier.newVerifier()
Expand Down
Loading