Executing Java code like a script
TL;DR
- JEP 330 allows us to run casual (e.g. scripting purpose) Java code without
javac
Traditional Java code execution
Let’s say we have the following Main.java and Word.java.
// Main.java
public class Main {
public static void main(String[] args) {
for (Word str : Word.values()) {
System.out.println(str.getWord());
}
}
}// Word.java
public enum Word {
A("apple"),
B("banana"),
C("cat"),
D("dog")
;
private final String str;
Word(String str) {
this.str = str;
}
public String getWord() {
return this.str;
}
}We generally compile Java code into Java class files which JVM loads with java command. Here is an example to run the above Java program with the process.
$ javac Main.java Word.java
$ java Main
apple
banana
cat
dogHowever, I sometimes want to execute Java code casually without the javac step. Using IDE plugins enable us to skip the javac compiles, but I would rather run Java program as we do with Shell scripts and Ruby on my terminal. For example,
java Main.javaSingle file execution without explicit compiles
Fortunately, I found JEP 330: Launch Single-File Source-Code Programs, which allows me to execute Java code without javac. This feature is named “source-file mode” and we can gather all necessary classes in a single Java file (e.g. Main.java). Then, we can execute the code using java command. With the example code above, we can put all code into the following Main.java.
// Main.java
public class Main {
public static void main(String[] args) {
for (Word str : Word.values()) {
System.out.println(str.getWord());
}
}
}
public enum Word {
A("apple"),
B("banana"),
C("cat"),
D("dog")
;
private final String str;
Word(String str) {
this.str = str;
}
public String getWord() {
return this.str;
}
}Then, we can execute the code as follows.
$ java Main.java
apple
banana
cat
dog