.java file, list any libraries in a comment at the top, and run it with jbang File.java. No pom.xml, no project directory, no separate compile step. This post starts there, then builds up to a command line tool with real arguments, a whole Spring Boot web application in one file, your own project templates, scripts you run straight from a URL, and a native binary — and every example in the main text was run, with the output committed.
Verified versions. JBang 0.132.1 (the newestjbang-clijar on Maven Central) on Temurin JDK 25.0.5.1 (LTS); picocli 4.7.7; Jackson 3.3.0 (tools.jackson); Spring Boot 4.2.0; Oracle GraalVM 25.0.4 for the native step.
One honest gap. GitHub’s releases page lists v0.143.0 as the newest stable JBang (tagged “30 Oct”; the page shows no year), so Maven Central is eleven minor versions behind. I could not download GitHub release assets from my build environment, so I ran 0.132.1 and did not run 0.143.0. Its release notes list alias version pinning (alias:version@catalog) and replacing SDKMAN with mise; nothing in them touches the commands shown here, but I have not diffed the releases in between. If you install with the official script you will get the newer one — run the examples and compare.
Runnable code: every script is in thejbangmodule ofjava-devops-demo, and every console block is copied from a file in its output directory. There is deliberately nodocs/folder: the explanation is this page, and the folded sections below hold the deeper material.
A twenty-line program should not need a build file
If you only want to try a library, parse a file, call an API once, or write a small command line tool, the usual route is a build tool project: apom.xml, a src/main/java/... tree, a package command, then a java -cp line that is hard to remember. All of that exists for good reasons when a project has many modules, tests and a release process. It is overkill when the program is one file.
//, the file is still plain, valid Java that any editor and compiler accepts.
Going deeper: where JBang sits next to Maven, Gradle and jshell
JBang is a launcher and a dependency resolver, not a build system. It uses the same Maven resolver that build tools use, so artifacts land in the ordinary~/.m2/repository (visible in the info classpath output in section 3). It compiles with the javac of the JDK it picks, caches the resulting jar, and runs it. Compared with jshell, a JBang script is a normal compiled class: it has a main, can be exported as a jar, and can be shared as a file. Compared with the Java launcher’s own source-file mode (java Hello.java), JBang adds the part that mode lacks — dependencies, templates, a script catalog and JDK management.See the JBang documentation for the full guide.
The smallest thing that works
Here is the whole ofHello.java (also in the repository as Hello.java). The first line is a trick: on Linux and macOS, a file that starts with ///usr/bin/env jbang "$0" "$@" ; exit $? can be made executable and run as ./Hello.java. To Java it is just a comment. The second line, //JAVA 25+, asks for Java 25 or newer.
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 25+
/**
* The classic shape: one file, one class, a static main.
* The first line is a shebang trick so ./Hello.java works on Linux/macOS once chmod +x.
*/
public class Hello {
public static void main(String[] args) {
String who = args.length > 0 ? String.join(" ", args) : "world";
System.out.println("Hello, " + who + "!");
System.out.println("Running on Java " + Runtime.version().feature()
+ " (" + System.getProperty("java.vendor") + ")");
}
}
Running it twice shows what the tool is doing. The first run prints Building jar and takes noticeably longer; the second finds the compiled jar in JBang’s cache and goes straight to running it. The wall-clock figures are from a two-vCPU sandbox and include starting JBang itself, so treat them as indicative, not as a benchmark. They come from 01-hello.txt.
# Cold run (empty JBang cache) then warm run, same script
$ jbang Hello.java Ankur
[jbang] Building jar for Hello.java...
Hello, Ankur!
Running on Java 25 (Eclipse Adoptium)
[wall clock: 5.745s]
$ jbang Hello.java Ankur
Hello, Ankur!
Running on Java 25 (Eclipse Adoptium)
[wall clock: 2.338s]
java command to run. Steps two and three are skipped whenever the cache already holds a jar for this script.
See what JBang decided
jbang info tools prints the decisions as JSON: which main class it found, which Java version you asked for and which JDK it will use, and the compiler options. Notice that it compiles with -g -parameters by default.
$ jbang info tools Hello.java
{
"originalResource": "Hello.java",
"backingResource": "/tmp/work/jbang/Hello.java",
"applicationJar": "/tmp/tmp.RXxYNQBWOn/cache/jars/Hello.java.af0224835723899ff208d77a8e96fa9f8c064e617b7dbc225df29b5021aab8a0/Hello.jar",
"mainClass": "Hello",
"resolvedDependencies": [],
"javaVersion": "25",
"requestedJavaVersion": "25+",
"availableJdkPath": "/tmp/tools/jdk-25.0.5.1+2",
"compileOptions": [
"-g",
"-parameters"
],
"sources": [
{
"originalResource": "Hello.java",
"backingResource": "/tmp/work/jbang/Hello.java"
}
],
"docs": {}
}
Going deeper: why the jbang jar prints a command and exits with 255
I wanted to run the Maven Central jar without the official launcher script, and the first attempt printed a longjava -classpath ... line and returned status 255 instead of running my program. That is the design: the Java part of JBang does the slow, JDK-independent work and prints the final command; the thin shell (or PowerShell) launcher evals it. This lets JBang switch JDKs per script without being locked to the JDK that launched it. scripts/jb.sh reproduces that handshake in under twenty lines if you want to see it, and is what the repository uses when no jbang launcher is installed.Practical consequence: if you embed the jar in another tool, check for exit status 255 and run what it printed.
Dependencies are a comment: //DEPS
A real tool needs libraries. You add them with //DEPS groupId:artifactId:version. Below is a command line program using picocli, a library that turns annotations into argument parsing, --help and --version. The full file is Greeter.java; you can also download Greeter.java.
//JAVA 25+
//DEPS info.picocli:picocli:4.7.7
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import java.util.concurrent.Callable;
/**
* A real command line tool in one file: argument parsing, --help and --version for free.
* The only build file is the //DEPS line above.
*/
@Command(name = "greeter", mixinStandardHelpOptions = true, version = "greeter 1.0",
description = "Greets people, optionally loudly.")
public class Greeter implements Callable<Integer> {
@Parameters(index = "0", description = "Who to greet.")
String name;
@Option(names = {"-l", "--loud"}, description = "Shout the greeting.")
boolean loud;
@Option(names = {"-n", "--times"}, defaultValue = "1", description = "Repeat count (default: ${DEFAULT-VALUE}).")
int times;
@Override
public Integer call() {
String msg = "Hello, " + name + "!";
for (int i = 0; i < times; i++) {
System.out.println(loud ? msg.toUpperCase() : msg);
}
return 0;
}
public static void main(String[] args) {
System.exit(new CommandLine(new Greeter()).execute(args));
}
}
The first run resolves the dependency from Maven Central, compiles, and runs. The output below is from 03-picocli-greeter.txt.
$ jbang Greeter.java --help
[jbang] Resolving dependencies...
[jbang] info.picocli:picocli:4.7.7
[jbang] Dependencies resolved
[jbang] Building jar for Greeter.java...
Usage: greeter [-hlV] [-n=<times>] <name>
Greets people, optionally loudly.
<name> Who to greet.
-h, --help Show this help message and exit.
-l, --loud Shout the greeting.
-n, --times=<times> Repeat count (default: 1).
-V, --version Print version information and exit.
$ jbang Greeter.java --loud --times 2 Ankur
HELLO, ANKUR!
HELLO, ANKUR!
jbang info classpath answers “where did that library come from?”. The answer is the compiled script jar plus the picocli jar in your ordinary local Maven repository — the same ~/.m2 a Maven build would use.
$ jbang info classpath Greeter.java
/tmp/tmp.RXxYNQBWOn/cache/jars/Greeter.java.5779a46c55f3fbe373ce3efdcca5ec2bb019e2179eee9b52e6fc7d76d8acbec9/Greeter.jar:/root/.m2/repository/info/picocli/picocli/4.7.7/picocli-4.7.7.jar
A second example, Pretty.java (download), pretty-prints JSON from standard input with Jackson 3. Note the new tools.jackson group id; Jackson 3 moved its packages. The Jackson ObjectMapper and JsonMapper guide on this blog explains what else changed.
//JAVA 25+
//DEPS tools.jackson.core:jackson-databind:3.3.0
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.json.JsonMapper;
/** Reads JSON on stdin, writes it back pretty-printed. A tiny jq-lite in one file. */
public class Pretty {
public static void main(String[] args) throws Exception {
var mapper = JsonMapper.builder().enable(SerializationFeature.INDENT_OUTPUT).build();
var tree = mapper.readTree(System.in);
System.out.println(mapper.writeValueAsString(tree));
}
}
$ echo '{"a":1,"b":[1,2,{"c":null}]}' | jbang Pretty.java
[jbang] Resolving dependencies...
[jbang] tools.jackson.core:jackson-databind:3.3.0
[jbang] Dependencies resolved
[jbang] Building jar for Pretty.java...
{
"a" : 1,
"b" : [ 1, 2, {
"c" : null
} ]
}
The output is from 04-jackson-pretty.txt.
Going deeper: the directives you will actually use
These come from JBang’s script directives reference; I ran//DEPS, //JAVA, //SOURCES, //FILES, //RUNTIME_OPTIONS and the BOM form, and took the rest from the page without running them.| Directive | What it does |
|---|---|
//DEPS g:a:v | Add a Maven dependency (ran above). g:a:v@pom imports a BOM; the first @pom manages the versions of the others (ran in section 6). |
//JAVA 25+ | Required Java version; + means “or newer”. JBang finds or installs a matching JDK (ran in sections 4 and 10). |
//SOURCES a.java b.java | Compile extra source files with this one (ran in section 5). |
//FILES x.txt | Make resource files available at run time and in an exported jar (ran in section 5). |
//REPOS | Replace the default Maven Central lookup with other repositories (not run). |
//RUNTIME_OPTIONS / //COMPILE_OPTIONS | JVM and javac flags. SpringApp.java uses the first to set a port. |
//PREVIEW | Enable JDK preview features (not run). |
//NATIVE_OPTIONS | Flags for native-image (not run; see section 9). |
//GAV, //MAIN, //MANIFEST, //CDS, //JAVAAGENT, //KOTLIN, //GROOVY, //DESCRIPTION, //DOCS | Export coordinates, main-class override, manifest entries, class-data sharing, agents, other languages, catalog text (not run). |
Pin every version. A script with an unpinned or ranged dependency can change behaviour between two runs on the same day; the guide I read documents exact versions only, which is the safe habit anyway.
No class, no public static void main: compact source files
Java 25 finalised compact source files (JEP 512). A file can contain just fields and methods; the compiler wraps them in an implicit class named after the file, and void main() is a valid entry point. JBang runs such files directly. See the file at CompactHello.java or download CompactHello.java.
//JAVA 25+
// A compact source file (JEP 512, final in Java 25): no class, no "public static",
// no String[] args. The compiler wraps this in an implicit class named after the file.
String greeting = "Hello from a compact source file";
void main() {
IO.println(greeting);
IO.println("Implicit class: " + getClass().getName());
}
$ jbang CompactHello.java
[jbang] Building jar for CompactHello.java...
Hello from a compact source file
Implicit class: CompactHello
The run is recorded in 02-compact-source-file.txt. getClass().getName() printing CompactHello is the implicit class at work, and IO.println is the new java.lang.IO helper.
This only works on Java 25. The same file with//JAVA 21makes JBang download JDK 21 and then fail insidejavac, because compact source files were still a preview feature on 21. The error text is copied from the real run (see08-broken-CompactNoJava25.txt):Fix it by asking for/tmp/work/jbang/broken/CompactNoJava25.java:2: error: unnamed classes are a preview feature and are disabled by default. void main() { ^ (use --enable-preview to enable unnamed classes)//JAVA 25+.
Going deeper: classic main versus compact main
Both forms are fine under JBang; a compact file is shorter, but its implicit class lives in the unnamed package, which matters for frameworks that scan packages (see the Spring Boot section). For anything a framework must scan, or that needs several top-level types, use a normal class. JBang reportsmainClass in jbang info tools (section 2), which is the quickest way to see what it chose.
When one file is not enough: //SOURCES and //FILES
Scripts grow. Rather than leaving single-file mode, list the extra files you need. //SOURCES compiles additional .java files next to the main one, and //FILES puts resource files on the classpath. The two source files are multi/Main.java and multi/Shout.java.
//JAVA 25+
//SOURCES Shout.java
//FILES banner.txt=banner.txt
import java.io.InputStream;
/**
* More than one file: //SOURCES pulls in Shout.java, //FILES makes banner.txt
* available on the classpath as a resource.
*/
public class Main {
public static void main(String[] args) throws Exception {
try (InputStream in = Main.class.getClassLoader().getResourceAsStream("banner.txt")) {
System.out.print(new String(in.readAllBytes()));
}
System.out.println(Shout.shout("one script, two sources, one resource"));
}
}
$ jbang Main.java
[jbang] Building jar for Main.java...
=== multi-file JBang demo ===
ONE SCRIPT, TWO SOURCES, ONE RESOURCE!
Output from 05-multi-source.txt. A banner file read as a classpath resource and a helper class from a second source file, both without a build file.
Going deeper: relative paths and exported jars
Paths in//SOURCES and //FILES are relative to the main script, so you can run it from any directory. //FILES entries are also embedded when you export a jar (section 8), according to the docs; I did not test an exported jar of this example. The a=b form renames a file on the way in; I used the same name on both sides.
A whole Spring Boot web application in one file
JBang can run a Spring Boot application from a single file. Two directives do the work: a BOM import (@pom) so that the starter needs no version of its own, and the starter itself. The file is SpringApp.java (download).
//JAVA 25+
//DEPS org.springframework.boot:spring-boot-dependencies:4.2.0@pom
//DEPS org.springframework.boot:spring-boot-starter-webmvc
//RUNTIME_OPTIONS -Dserver.port=8089 -Dspring.main.banner-mode=off
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* A whole Spring Boot web application in a single file. The BOM (@pom) pins every
* Spring Boot dependency, so the starter needs no version of its own.
*/
@SpringBootApplication
@RestController
public class SpringApp {
@GetMapping("/hello")
String hello() {
return "Hello from a single-file Spring Boot app";
}
public static void main(String[] args) {
SpringApplication.run(SpringApp.class, args);
}
}
Run it, then call it from another terminal. Output from 06-spring-boot-single-file.txt (the log lines are filtered to the ones that matter; the filtering is in scripts/run-all.sh):
$ jbang SpringApp.java
[log lines that matter, timestamps/PIDs trimmed]
INFO demo.SpringApp : Starting SpringApp using Java 25.0.5.1 with PID 22275 (/tmp/tmp.RXxYNQBWOn/cache/jars/SpringApp.java.3f7221da265b2f6554670ab927989c9962b804151b313b88dc6e785f1aba42b3/SpringApp.jar started by root in /tmp/work
INFO o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 8089 (http) with context path '/'
INFO demo.SpringApp : Started SpringApp in 4.875 seconds (process running for 5.977)
$ curl -s localhost:8089/hello
Hello from a single-file Spring Boot app
The trap: the default package. My first version of this file had nopackageline, because JBang scripts normally do not need one. Spring Boot refused to start, and the failure is confusing because the application context never gets as far as your code. The fingerprint is a warning that the context is unlikely to start due to a @ComponentScan of the default package, followed by an APPLICATION FAILED TO START message about a bean namederrorPageRegistrarBeanPostProcessoralready being defined (the committed line is cut at 230 characters by the log filter). The failing variant is kept asbroken/SpringDefaultPackage.javaand its output is in07-spring-default-package-failure.txt:The fix is one line —** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package. APPLICATION FAILED TO START The bean 'errorPageRegistrarBeanPostProcessor', defined in class path resource [org/springframework/boot/web/servlet/support/ErrorPageFilterConfiguration.class], could not be registered. A bean with that name has already been defipackage demo;at the top — and JBang handles a package-declared script without any extra configuration.
Going deeper: what the BOM line buys you, and when to stop
//DEPS org.springframework.boot:spring-boot-dependencies:4.2.0@pom imports Spring Boot’s dependency management, so spring-boot-starter-webmvc and anything else you add resolve to compatible versions. The starter is named webmvc in Boot 4; the version lookup for the older spring-boot-starter-web name on Maven Central returned nothing when I tried it. //RUNTIME_OPTIONS -Dserver.port=8089 sets the port without a properties file.A single-file Spring Boot app starts in about five seconds here after the first compile (
Started SpringApp in 4.875 seconds); I did not compare it with a Maven-built run of the same code. It is the right tool for a demo, a reproduction of a bug report, or an internal webhook receiver. Once you need configuration profiles, tests, several controllers and a CI pipeline, move to a build tool project; jbang export (section 8) and the gradle and maven export subcommands that the CLI lists exist for that hand-off, though I did not run them.
Templates, catalogs and aliases
Once you have written the same skeleton three times, make it a template.jbang init creates a new script from one. JBang ships a few (run jbang template list; the first lines showed agent, cli and gpt among others), and you can add your own. The repository has a picocli skeleton at templates/tool.java.qute and a catalog file that registers it, jbang-catalog.json.
@Command(name = "{baseName}", mixinStandardHelpOptions = true, version = "{baseName} 0.1")
public class {baseName} implements Callable<Integer> {
Registering and using it, from 09-templates.txt:
$ jbang template add -f jbang-catalog.json --name tool '{basename}.java=tool.java.qute'
[jbang] Template 'tool' added to 'jbang-catalog.json'
[...]
$ cat jbang-catalog.json
{
"templates": {
"tool": {
"file-refs": {
"{basename}.java": "tool.java.qute"
},
"description": "Picocli CLI skeleton",
"properties": {}
}
}
}
[...]
$ jbang init -t tool Slugify.java
[jbang] File initialized. You can now run it with 'jbang Slugify.java' or edit it using 'j
$ sed -n 9,10p Slugify.java
@Command(name = "Slugify", mixinStandardHelpOptions = true, version = "Slugify 0.1")
$ jbang Slugify.java Hello World
[jbang] Building jar for Slugify.java...
Slugify processed: Hello World
The same catalog file also defines aliases: short names for scripts, so jbang greeter -n 2 Ankur works from the directory that holds the catalog. From 10-catalog-aliases.txt:
$ jbang alias list
greeter
Picocli greeter CLI
/tmp/work/jbang/Greeter.java
pretty
Pretty-print JSON from stdin (Jackson 3)
/tmp/work/jbang/Pretty.java
$ jbang greeter -n 2 Ankur
Hello, Ankur!
Hello, Ankur!
Three template traps, all found by running it.
1. Placeholders in file contents need.qute. My first template was a plaintool.javawith{basename}inside the class.jbang initcreated the file but left{basename}in the code, and the compiler reported nine errors. Plain files only get{basename}substituted in the file name. To substitute inside the file, name it with a.qutesuffix and use{baseName}(camel case) in the content. Qute is the template engine behind.qutefiles, so check that the generated file still compiles; mine did.
2. Left side is the new name, right side is your file.jbang template add --name tool '{basename}.java=tool.java.qute'works; the reverse fails with File could not be found or read: ‘{basename}.java’. The documentation’s prose says “source=target” but its examples read the other way round; trust the examples.
3. Without-f, the template goes into your global catalog. Run from a directory with no catalog,jbang template addreported that it wrote tojbang-catalog.jsonunderJBANG_DIR, not the current folder. Pass-f jbang-catalog.jsonto keep it with the project.
Going deeper: catalogs, properties and sharing templates
A catalog is a JSON file withaliases, templates and optionally catalogs that reference other catalogs; the committed jbang-catalog.json is a working example with both. JBang picked up the jbang-catalog.json in the current directory, which is how the alias list above worked; it also keeps a user-level catalog under JBANG_DIR. Any -Dkey=value given to jbang init becomes {key} inside a .qute template, so give each property a default. The templates page covers properties and the --verbose trick for inspecting a half-initialised template; I read these and did not run the property example.To share a catalog, publish the JSON and let people add it by URL; the docs front page shows a
jbang <cmd>@<your-org> form for running published tools. I did not test that route because GitHub was not reachable from my environment.
Sharing a script: export, or run it from a URL
Two ways to hand a script to someone else.jbang export portable builds a jar that runs with plain java -jar. I ran it on the same machine that built it and did not test it on another, so check that before you rely on it. Output from 11-export-portable.txt:
$ jbang export portable -O /tmp/greeter-portable.jar Greeter.java
[jbang] Updating jar...
[jbang] Exported to /tmp/greeter-portable.jar
$ ls greeter-portable*
greeter-portable.jar
$ java -jar greeter-portable.jar Ankur
Hello, Ankur!
The other way is to give them a URL. JBang can run a script straight from one. I uploaded Hello.java to this site’s media library so you can try it: Hello.java. Running a script from a URL means running someone else’s code, so JBang refuses by default. The sequence below is from 13-remote-run-and-trust.txt (trimmed to the key lines; [...] marks where I cut):
$ jbang https://ankurm.com/wp-content/uploads/2026/12/Hello.java Remote
[jbang] https://ankurm.com/wp-content/uploads/2026/12/Hello.java is not from a trusted source thus not running it automatically.
[...]
[jbang] [ERROR] https://ankurm.com/wp-content/uploads/2026/12/Hello.java is not from a trusted source and user did not confirm trust thus aborting.
[...]
[exit status: 10]
[...]
$ jbang trust add https://ankurm.com/wp-content/uploads/
[jbang] Trusting permanently: [https://ankurm.com/wp-content/uploads/]
[...]
$ jbang https://ankurm.com/wp-content/uploads/2026/12/Hello.java Remote
[jbang] Building jar for Hello.java...
Hello, Remote!
Running on Java 25 (Eclipse Adoptium)
[...]
$ grep -v '^//' $JBANG_DIR/trusted-sources.json
[
"https://ankurm.com/wp-content/uploads/"
]
Remote scripts are code execution. Trust the narrowest prefix you can: herejbang trust add https://ankurm.com/wp-content/uploads/, not*, which the tool itself warns “disables url protection”. The refusal exits with status 10, and when there is no terminal to answer the prompt it waits 30 seconds and cancels — so a CI job will fail slowly rather than run something untrusted. Trust is recorded intrusted-sources.jsonunderJBANG_DIR.
Download the example scripts
| Script | What it shows | Download |
|---|---|---|
Hello.java | smallest script, shebang line | Hello.java |
CompactHello.java | compact source file (Java 25) | CompactHello.java |
Greeter.java | picocli command line tool | Greeter.java |
Pretty.java | Jackson 3 JSON pretty-printer | Pretty.java |
SpringApp.java | Spring Boot 4.2 in one file | SpringApp.java |
Going deeper: the other export targets
The CLI reference listsexport subcommands portable, local, mavenrepo, native, fatjar, jlink, gradle and maven; I ran only portable. The names suggest what each does (fatjar, jlink, and gradle/maven for graduating a script to a project), and the CLI also has jbang app install for putting a script on your PATH; read the CLI reference before using any of them.
Native images: slow to build, instant to start
With GraalVM’snative-image installed, jbang --native Hello.java compiles the script to a native executable and runs it. It needs GraalVM as the active JDK (I used Oracle GraalVM 25.0.4 plus the usual C toolchain). Output from 12-native.txt:
# native-image 25.0.4 2026-07-21
$ jbang --native Hello.java Native
[jbang] Building jar for Hello.java...
[jbang] log: /tmp/jbang18248476024474165891native-image
Hello, Native!
Running on Java 25 (Oracle Corporation)
[wall clock: 154.486s]
$ jbang --native Hello.java Native # second run, binary cached
Hello, Native!
Running on Java 25 (Oracle Corporation)
[wall clock: 1.350s]
The first build took 154 seconds on a two-vCPU machine. The binary is cached, so the second run is fast, but it still pays for starting JBang. The cached binary is 7,866,632 bytes (the listing is in the same transcript file). Running it directly and comparing with the same program on the JVM:
$ Hello.bin Native # the cached binary, no JBang, no JVM
Hello, Native!
Running on Java 25 (Oracle Corporation)
[wall clock: 0.005s]
$ java -cp Hello.jar Hello Native # same program on the JVM
Hello, Native!
Running on Java 25 (Oracle Corporation)
[wall clock: 0.277s]
jbang costs 1.35 s because JBang itself is a JVM program. If start-up time is why you want native, export the binary (jbang export native) and run that.
Native is a trade, not an upgrade. The binary is specific to the operating system and CPU you built it on, the build is slow, and anything that relies on reflection, dynamic proxies or resources found at run time needs extra configuration or fails with an UnsupportedFeatureError. JBang’s documentation says to test the native build separately from the JVM one. For a one-line hello it is a clean win; for the Spring Boot script above it is a different project. This blog’s Spring Boot start-up comparison covers that side.
Going deeper: native options, the tracing agent and PGO
Options go in a//NATIVE_OPTIONS directive or on the command line as --native-option=.... The native-images page documents flags such as --no-fallback, -O2, --gc=serial, a way to generate reflection configuration with the tracing agent (jbang --jvm=graalvm --runtime-option="-agentlib:native-image-agent=config-output-dir=config" myapp.java), and profile-guided optimisation. I ran none of these; only the plain --native build above. The page also notes that picocli apps need info.picocli:picocli-codegen on the annotation path for native builds. The 0.143.0 release notes mention an experimental JBANG_USE_NATIVE=true opt-in, which I have not tried.Source: JBang native images.
What goes wrong, and what it looks like
Three failures are worth recognising on sight. All three are kept inbroken/ and their output is committed.
A dependency version that does not exist. //DEPS info.picocli:picocli:9.9.9 (broken/MissingDep.java) fails at resolution with exit status 1:
$ jbang broken/MissingDep.java
[jbang] Resolving dependencies...
[jbang] info.picocli:picocli:9.9.9
[jbang] [ERROR] Could not read artifact descriptor for info.picocli:picocli:jar:9.9.9
[jbang] Run with --verbose for more details. The --verbose must be placed before the jbang command. I.e. jbang --verbose run [...]
[exit status: 1]
A Java version nobody has. //JAVA 99 (broken/NeedsJava99.java) exits with status 4:
$ jbang broken/NeedsJava99.java
[jbang] [ERROR] No suitable JDK was found for requested version: 99
[jbang] Run with --verbose for more details. The --verbose must be placed before the jbang command. I.e. jbang --verbose run [...]
[exit status: 4]
JBang installs JDKs for you, and says so in one line. The//JAVA 21script in section 4 made JBang download JDK 21 into its own cache and print Default JDK set to 21. In my run the nextHello.javastill used 25 becauseJAVA_HOMEpointed at 25. WithoutJAVA_HOMEset, check which JDKjbang info toolsreports before assuming. Run it with--offlineon a build machine that must not download anything.
Going deeper: the other problems the troubleshooting guide lists
From JBang’s troubleshooting page; I did not reproduce these. The cache lives under~/.jbang/cache (move it with JBANG_DIR); jbang cache clear resets it, and jbang --fresh jdk install 21 fixes a corrupt JDK download. For slow dependency downloads configure a mirror in ~/.m2/settings.xml or point JBANG_MAVEN_SETTINGS at another file, and raise JBANG_DOWNLOAD_RETRY (default 5). On Windows the recurring causes are long paths, antivirus scanning the cache, a restrictive PowerShell execution policy, CRLF line endings in scripts, and symbolic-link errors from jbang edit (use jbang edit -b).
Should you use JBang at all?
Yes for scripts, demos and tools; no for applications. JBang is excellent when the program fits in one to a few files: bug reproductions to attach to an issue, a data-fixing one-off, a small internal tool, or a code sample readers can run with one command. It is the wrong tool for a service with modules, tests and a pipeline — there, a build tool is the better source of truth, and JBang’s only role is the first ten minutes.
Three cautions. Pin dependency versions in every script. Treatjbang trustas a security decision. And keep the version you test on in mind: the newest JBang on Maven Central is not the newest JBang, so install it the official way and re-run the examples on whatever you get.
Further reading
- Companion repository module:
java-devops-demo/jbang— every script and every captured output used above - Jackson ObjectMapper and JsonMapper (Jackson 2 and 3): Complete Guide — what changed in Jackson 3, used in
Pretty.java - Spring Boot with CRaC, the AOT cache and a native image — start-up trade-offs for the Spring side of section 9
- JBang documentation
- JBang script directives
- JBang templates
- JBang native images
- JBang releases on GitHub
- JEP 512: Compact Source Files and Instance Main Methods
- picocli
No Comments yet!