I can only reproduce the behavior when using java StaticBlockPrint.java
but then, in all versions since JDK-11.
When I compile with javac
and run with java StaticBlockPrint
, all versions since Java 7, including 18.0.2.1, consistently produce an error regarding the missing main method.
Technically, the difference is tiny. The class initializer ends with System.exit(0);
, so when it is executed before the missing main method is about to be reported, the process is terminated without an error message.
The following program demonstrates two variants of how a launcher could be implemented
class Initializer {
public static void main(String... arg) {
ClassLoader cl = Initializer.class.getClassLoader();
// variant 1
try {
cl.loadClass("A").getMethod("main");
}
catch(Throwable t) {
System.out.println("A: " + t);
}
// variant 2
try {
Class.forName("B", true, cl).getMethod("main");
}
catch(Throwable t) {
System.out.println("B: " + t);
}
}
}
class A {
static {
System.out.println("A initialized");
}
}
class B {
static {
System.out.println("B initialized");
}
}
A: java.lang.NoSuchMethodException: A.main()
B initialized
B: java.lang.NoSuchMethodException: B.main()