Installing jbang
- ASDF is what i used (works in linux and mac)
Basics
- Minimum requirement Java 8
- argument to jbang
- Kotlin and groovy are experimental
Extension | operation |
---|---|
.java | Compile the java |
.jsh | Jshell |
.md | Java code inside markdown |
Folder | Main.java file executed |
Get started
jbang Sample.java
Sample.java
public class Sample { public static void main(String[] args) { System.out.println("Hello, this is a simple Java program!"); } }
Managing Java version
- Adopt JDK will be used
List jdk installed in the system
jbang jdk list
Install particular java version
jbang jdk install 14
List all the available version by jbang
jbang jdk list --available
Set default jdk version
jbang jdk default 17
Uninstall particular version
jbang jdk uninstall 17
JDK home path
jbang jdk home
Install java from existing path
jbang jdk install 17 <PATH> jbang jdk install 17 `sdk home java 17.0.4.1-tem`
Environment variable details
jbang jdk java-env
Simple example
java init --template=cli hello.java
JFX
Let's look into few examples
//JAVA 21+ //DEPS org.openjfx:javafx-controls:21:${os.detected.jfxname} //DEPS org.openjfx:javafx-graphics:21:${os.detected.jfxname} //RUNTIME_OPTIONS --enable-native-access=javafx.graphics import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class jfx extends Application { @Override public void start(Stage stage) { String javaVersion = System.getProperty("java.version"); String javafxVersion = System.getProperty("javafx.version"); Label l = new Label("Hello, JavaFX " + javafxVersion + ", running on Java " + javaVersion + "."); Scene scene = new Scene(new StackPane(l), 640, 480); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } }
Jbang edit
jbang edit myfile.java
For Emacs/Vim (in sandbox mode), For editor that doesn't support jbang
jbang edit -b myfile.java
Live editing
jbang edit --live
Jshell integration
Simple jsh file
// Import necessary classes import java.util.ArrayList; // Create a list and add elements ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Print the list System.out.println("Fruits: " + fruits); // Iterate over the list for (String fruit : fruits) { System.out.println(fruit); }
Execute the above script using
jbang Sample.jsh
We can spawn a interactive shell using the following command
jbang --interactive Sample.jsh
Java debugging
jbang --debug hello.java
attach with jdb
jdb -attach IP_ADDRESS:PORT
Export
Gradle
jbang export gradle --group org.acme --artifact myapp --version 1.0.0-SNAPSHOT hello.java
Maven
jbang export maven --group org.acme --artifact myapp --version 1.0.0-SNAPSHOT hello.java
Java Flight Recorder
jbang --jfr myapp.java
Want more
- https://www.jbang.dev/try/ (run it in the browser)
- Check their docs
- It can also generate Native code using GraalVM.