What if one want to quickly setup a Java project without wanting to fire overkilled weapon like Maven, Ant or Gradle ? 🤔
Is the JDK really a Software Development Kit if one need to rely on other software code a solution ? 🤔
Starting with Java 11 and JEP 330, the runtime introduce
a mechanism allowing the java command line to accept a single source file as input
and running it without requiring the compilation.
Then, a shebang can be put on top of the file to make it runnable as any (shell/perl/python/ruby) script
#!/usr/bin/env -S java --source 21
public class Hello {
public static void main(String...args) {
System.out.println("Hello, World!");
}
}NOTE: be sure that the first
javaexecutable found in${PATH}has version higher or equal to the source file.
- works like a charm in interactive mode using JEnv
- works as expected in batch mode when PATH is exported like following: PATH="${JAVA_HOME}/bin:${PATH}"
Or, if one want to be more precise, but less portable:
#!/usr/lib/jvm/java-21/bin/java --source 21
public class Hello {
public static void main(String...args) {
System.out.println("Hello, World!");
}
}NOTE:
--source 21is mandatory to tell the JVM to turn into script mode
The java.lang.Runtime allows to run command lines from the JVM.
The java.net.http module allows to make HTTP requests.
And with some elbow grease, here comes a way to manage a Java project lifecycle, including dependency management, in a tiny portable fashion.
The more complex the lifecycle, the harder it is to hack. First step is to list the acceptable tradeoffs, ex:
- phases are always delegating to each other in order or precedence
- there is no way to launch more than one phase at a time
Some acceptance criteria:
- it's a script, it has to be self documented
- do not need anything else than the JDK
- do not store dependencies in the source control
- allow some local (per environment) customization
- unlike Python scripts for example, the script can not be named
script.java😕 - project dependencies are only known by the script, IDEs like IDEA, Eclipse, or any power editing tool like NeoVim, Visual Studio Code or Sublime Text will be hard to sync (but it's not impossible 😉)
- because the main class is in default package, can not
import staticanything inside 😕 - it does not scale! works well on a tiny project, but you can forget multi-modules 😁
This project is for educational purpose only.
This is just a proof of concept:
- yes, it's possible to replace Maven, Ant or Gradle
- no, it's not worth it