Why do Single-File Source-Code programs implicitly run the first declared class?
Ethan McCue
ethan at mccue.dev
Sat Feb 12 03:02:03 UTC 2022
While testing some serialization warnings I stumbled upon this nugget of
behavior on the Single-File Source-Code mode
In source-file mode, the effect is as though the source file is compiled
into memory, and the first class found in the source file is executed. Any
arguments placed after the name of the source file in the original command
line are passed to the compiled class when it is executed.
So if you have a file named Example.java with these contents
class ABC {}
public class Example {
public static void main(String args[]) {
System.out.println(new ABC());
}
}
Then the result of running the file directly and compiling then running the
file will diverge.
$ java Example.java
error: can't find main(String[]) method in class: ABC
$ javac Example.java
$ java Example
ABC at 251a69d7
I don't think this is a bug since it is documented behavior both on the man
page and JEP 330, but does anyone have a record of what the reasoning for
the decision was? (At least as opposed to the "obvious" behavior of
requiring a class the same name as the file)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20220211/bba6f817/attachment.htm>
More information about the compiler-dev
mailing list