New candidate JEP: 445: Flexible Main Methods and Anonymous Main Classes (Preview)

Andrew Evers andrew.evers at gmail.com
Thu Apr 13 14:30:41 UTC 2023


Hi,

I really like the idea of reducing the amount of boilerplate required to
get to a simple Java program.

Two comments:
1. Would it be at all possible to consider a main that returns int?
Operating systems that don't support it are free to disregard it, and it
feels better than System.exit(). It also allows skipping the idea of void,
which is somewhat of a holdover from C.
2. I have an idea for a slightly different approach to the problem that may
solve a few of the problems being proposed, and allows for imports, which
would make it more useful for scripting use cases.

Here are three examples showing the syntax.

Example 1:
{
  System.out.println("Hello, World");
}

Example 2:
import java.nio.*;

{
  Path filePath = Path.of("file.txt");
  String fileContent = new String(Files.readAllBytes(filePath));
  System.out.println("Content is " + fileContent);
}

Example 3:
import java.nio.*;

{
  Path filePath = Path.of("file.txt");
  String fileContent = new String(Files.readAllBytes(filePath));
  greet(fileContent);
}

void greet(String s)
{
  System.out.println("Content is " + s);
}

The rules are simple:
1. If the first non-whitespace is a {, then treat it as the block defining
the method public static void main(String [] args).
2. If the first non-whitespace is "import" then capture the imports.
3. If there is non-whitespace after the closing } in the main block,
include it before the class closing brace.

That is:

// import statements if any
class Main
{
  public static void main(String [] args)
  { // Content including { from source
  } // end of content, including }

  // Content after closing } in source, if any.
}

There are some minor fixups required on line numbers after the import
statements, these can be overcome by either ensuring that the additional
code takes up zero lines, or by fixing up the output of the compiler.

Regards,

Andrew.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20230413/6d54bba7/attachment-0001.htm>


More information about the amber-dev mailing list