Skip to content

Commit afd0245

Browse files
committed
Require a public no args constructor
Fixes #933
1 parent 521a2f3 commit afd0245

File tree

2 files changed

+47
-4
lines changed

2 files changed

+47
-4
lines changed

src/main/java/org/openrewrite/java/migrate/lang/MigrateMainMethodToInstanceMain.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,15 +106,16 @@ private boolean hasNoArgConstructor(J.ClassDeclaration classDecl) {
106106
.filter(J.MethodDeclaration::isConstructor)
107107
.collect(toList());
108108

109-
// If no constructors are declared, the class has an implicit no-arg constructor
109+
// If no constructors are declared, the class has an implicit public no-arg constructor
110110
if (constructors.isEmpty()) {
111111
return true;
112112
}
113113

114-
// Check if any explicit constructor is a no-arg constructor
114+
// Instance main requires a public no args constructor
115115
return constructors.stream()
116-
.anyMatch(ctor -> ctor.getParameters().isEmpty() ||
117-
(ctor.getParameters().size() == 1 && ctor.getParameters().get(0) instanceof J.Empty));
116+
.anyMatch(ctor -> (ctor.getParameters().isEmpty() ||
117+
(ctor.getParameters().size() == 1 && ctor.getParameters().get(0) instanceof J.Empty)) &&
118+
ctor.hasModifier(J.Modifier.Type.Public));
118119
}
119120

120121
private boolean isMainMethodReferenced(J.MethodDeclaration mainMethod) {

src/test/java/org/openrewrite/java/migrate/lang/MigrateMainMethodToInstanceMainTest.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,4 +373,46 @@ public static void main(String[] args) {
373373
)
374374
);
375375
}
376+
377+
@Test
378+
void doNotMigrateMainWithPrivateNoArgConstructor() {
379+
//language=java
380+
rewriteRun(
381+
java(
382+
"""
383+
class Foo {
384+
private Foo() {}
385+
public static void main(String[] args) {
386+
System.out.println("Hello, World!");
387+
}
388+
}
389+
"""
390+
)
391+
);
392+
}
393+
394+
@Test
395+
void migrateMainWithPublicNoArgConstructor() {
396+
//language=java
397+
rewriteRun(
398+
java(
399+
"""
400+
class Application {
401+
public Application() {}
402+
public static void main(String[] args) {
403+
System.out.println("Hello, World!");
404+
}
405+
}
406+
""",
407+
"""
408+
class Application {
409+
public Application() {}
410+
void main() {
411+
System.out.println("Hello, World!");
412+
}
413+
}
414+
"""
415+
)
416+
);
417+
}
376418
}

0 commit comments

Comments
 (0)