Execute Java Code Like Unix Shell Script
By now, most of you might have heard about JDK9 JShell. If you are not aware of it, please click here. In this article, I am going to use JShell to show you how to execute Java code like Unix script.
Let me show you an example first and then go into details:
-
Open a file and save it with .txt by naming it as java_shell_code.txt
-
Write some Java code and execute the below command by passing the file name as an argument. You don’t need to declare a class. Just write statements or create methods and enjoy functional programming.
java_shell.code.txt
Let’s get into the details. In JDK 9, the Java team has introduced a new class called JShell.java under the jdk.jshell module. Using this class, we can evaluate Java code snippets, and create Java methods on the fly without declaring a class. If there are any errors in the Java code snippet it will provide a Snippet.status (either REJECTED or VALID). Source code analysiswill analyze the code till the semicolon and also resolves methods or class declarations, if there are any.
Here is the JShellScriptExecutor code. Please feel free to take and extend it as you want. You can also clone it from my GitHub page.
module-info.java
Enjoy the power of JShell and this class and start writing Java code like a Unix script and execute it like the way we execute .sh. Hope you like it!