JVM interop
Sprig compiles to Java before it runs, so the JDK's classes and Java libraries from Maven are right there for you to use. This page covers importing and calling Java classes, and the checks Sprig makes where your code meets Java.
The general rule is cautious. Unless Java says otherwise, Sprig assumes a returned value might be null: toString() is always a String, and a result the library annotates as non-null is a plain value (see below). In the other direction, what you pass to Java may not be null unless the parameter is annotated @Nullable.
The JVM interop reference has the complete rules. To plug Sprig into an existing build such as Gradle or Loom, see Gradle integration and Fabric mods. The Java interop cookbook works through five situations you'll meet again and again: nulls, exceptions, collections, callbacks and overloads.
Importing and calling Java classes
import java.lang.Math as Math
import java.lang.StringBuilder as StringBuilder
import java.time.LocalDate as LocalDate
print(Math.max(3, 9))
print(Math.abs(-4))
let builder = StringBuilder()
builder.append("Sprig")
builder.append("!")
print(builder.toString())
# Java reference results are nullable until checked.
let date = LocalDate.of(2026, 9, 25)
if date != null:
print(date.getYear())
print(date.getDayOfMonth())9
4
Sprig!
2026
25import java.lang.Math as Mathlets you refer to that class asMathin this file. Classes injava.langneed an import too; nothing is imported automatically.- Constructors, static methods, instance methods and static fields are all available through that name.
- When a method is overloaded, Sprig picks the overload by argument types. If none matches you get
SPR-JVM-MEMBER; if several fit equally well,SPR-JVM-AMBIGUOUS.
Check what Java returns
Objects returned by Java methods, including boxed types such as String and Integer, are treated as possibly null. Check them before use:
import java.lang.System as System
let version = System.getProperty("java.version")
if version != null:
print(version.length() > 0)trueMethods that return primitives (long, int, double, boolean and so on) never return null, so you can use those results directly.
In the other direction, an argument you pass to Java can't be null by default, even when the parameter type is Object. Check a T? value before you pass it to Java. Sprig reads nullability annotations: a result annotated @NotNull/@NonNull (or declared in a @NullMarked class or package) is a plain T, and a parameter annotated @Nullable accepts a T? or null. Run-time visible annotations (JSpecify, JSR-305) are read through reflection; annotations that live only in class files, like org.jetbrains.annotations, are read from the class file. Minecraft itself is JSpecify-annotated with @NullMarked on every package, so Item.use or Component.literal give you a plain value and only its @Nullable members are T?.
Type mapping
| Java | Sprig (primitive) | Sprig (boxed or object) |
|---|---|---|
long | Int | Int? |
int, short, byte | Int32 | Int32? |
double | Float | Float? |
float | Float32 | Float32? |
boolean | Bool | Bool? |
char | String | String? |
void | Unit | — |
String and other object types | — | the nullable Sprig type T? |
A few things to watch for:
Intnarrows tointwith a check. AnIntpassed where Java wants anintorInteger(a parameter, a constructor argument, a varargs element, a plain field assignment, or the result of a callback such as a comparator) is converted with a range check that fails at run time if the value doesn't fit. An exactlongoverload is still preferred, soMath.max(a, b)keeps using thelongversion. An integer literal that fits can also go to ashortorbyteparameter, but variables don't narrow to those, andFloatnever narrows tofloat, because that loses precision rather than range; usetoFloat32Exact().- A
charparameter takes a one-character literal.charandCharacterparameters accept only a string literal of exactly one UTF-16 unit."a"works, but"ab"doesn't, and neither does"😀", which one Javacharcan't hold. Sprig's own strings count positions in Unicode code points instead (seesprig help strings).
Catching Java exceptions
A Java checked exception can go in a Sprig throws clause and be caught with catch:
import java.net.URI as URI
import java.net.URISyntaxException as URISyntax
func parse_uri(text: String) -> String throws URISyntax:
let uri = URI(text)
if uri != null:
let host = uri.getHost()
if host != null:
return host
return ""
try:
print(parse_uri("https://example.com"))
print(parse_uri("::bad"))
catch problem: URISyntax:
print("bad uri")example.com
bad uriA caught Java exception shows Java's text, class name first, whether you print it, join it or call toString(). Its message is a String?, because Java's getMessage() may return null; check it before joining it. A Sprig Error shows only its message.
Java collections and Sprig collections
A Java List or Map never turns into a Sprig collection by itself, and a Sprig collection is never quietly passed where Java expects one. When you need to convert, use the functions in @std/jvm.spr:
import "@std/jvm.spr" as jvm
import java.util.ArrayList as ArrayList
let names = ArrayList[String]()
names.add("Ada")
names.add("Grace")
let snapshot = jvm.list_snapshot[String](names)
names.add("Linus")
print(snapshot.size())
print(names.size())
let copy = jvm.list_copy[String](snapshot)
print(copy.size())2
3
2list_snapshotandmap_snapshotcopy a Java collection, in order, into a read-only SprigListorMap. Whatever happens on the Java side afterwards doesn't affect the snapshot: above,namesgets a third name, andsnapshotstill has two.list_copyandmap_copygo the other way. They copy a Sprig collection into a separate JavaArrayListorLinkedHashMap, and from then on each side changes on its own.- A
nullelement, key or value in the Java collection causes a runtime error during the copy, sonullnever sneaks into a Sprig collection that doesn't allow it. - The element type has to match the source; a mismatch is caught at check time.
- All of these functions declare
throws Error, so handle that when you call them inside a function.
Generic Java classes
Imported Java classes and generic methods can take concrete type arguments, like ArrayList[String]() above.
- Type arguments are kept intact. You can write
List[Map[String, Int32]]orHost.method[String](value), and type arguments inherited from a superclass or interface are recognized too. - Results are still treated as possibly
null, sogeton anArrayList[String]returnsString?. - A generic method's own type arguments are inferred when its arguments fix every one of them (
Collections.sort(names),List.of(1, 2, 3)); one that only the result mentions, or that only a lambda would fix, is written out (Collectors.toList[Int]()). - A raw type (one with no type arguments) can't stand in for a parameterized one.
ArrayList[String]()works as aList[String]; a rawArrayList()doesn't. - Wildcards keep their bounds: a
List<? extends Number>result gives youNumber?elements, aList<? extends Number>parameter takes anArrayList[Int], and anything that would write through? extends(likeadd) is rejected. Generic arrays (T[]) aren't supported;sprig apishows the reason code.
Arrays and bytes
In Sprig, a Java array is a value you hold as a whole. You can receive it, check it for null and pass it unchanged to another Java method that expects a compatible array. You can't create, index, modify or loop over it in Sprig. There's no array syntax, and such code is rejected before javac runs, with SPR-SYNTAX-ERROR or SPR-TYPE-OPERAND. Overload resolution tells byte[], int[], String[] and Object[] apart, and whether one array type can be passed as another follows the JVM's own rules.
Binary data usually comes as byte[], and sprig.runtime.jvm.HostBytes converts it:
import sprig.runtime.jvm.HostBytes as HostBytes
let bytes = HostBytes.utf8("Sprig")
if bytes != null:
print(HostBytes.length(bytes))
print(HostBytes.hex(bytes))5
5370726967| Method | What it does |
|---|---|
HostBytes.utf8(text) | Encodes a string as UTF-8 bytes |
HostBytes.utf8String(bytes) | Decodes UTF-8 bytes into a string; invalid UTF-8 is a runtime error |
HostBytes.length(bytes) | The number of bytes, as an Int |
HostBytes.hex(bytes) | The bytes as a lowercase hex string |
You always call these conversions yourself; Sprig never converts implicitly.
Callbacks and varargs
Where a Java method wants a functional interface (an interface with one abstract method: Runnable, Comparator<T>, Consumer<? super T>, Predicate<? super T> and the rest of java.util.function), you can pass a Sprig function value. The compiler derives the fn(...) -> R it expects from the interface method with the usual type mapping and emits the Java adapter for you:
import java.util.ArrayList as ArrayList
import java.nio.file.Path as Path
import java.nio.file.Files as Files
import java.lang.String as JString
# A Sprig function value where Java wants a functional interface.
let names = ArrayList[String]()
names.add("grace")
names.add("ada")
names.sort(fn(a: String, b: String) => a.compareTo(b))
names.forEach(fn(name: String) => print(name))
print(names.removeIf(fn(name: String) => name.length() > 3))
# Varargs: the trailing arguments are packed, and zero of them is allowed.
let config = Path.of("etc", "sprig", "config.json")
if config != null:
print(config.getFileName())
print(Files.exists(config))
print(JString.join("/", "a", "b", "c"))ada
grace
true
config.json
false
a/b/c- Parameter types have to match exactly; a
voidmethod accepts a lambda with any result.Comparator.comparereturnsint, so the lambda returnsInt32(a.compareTo(b)does) or anInt, which is narrowed with a run-time range check like any otherIntpassed to anint. - Wildcards inside the interface's type arguments are fine: a lambda implementing
Consumer<String>is aConsumer<? super String>. - A method's own type variables are inferred only from plain arguments, never from a lambda:
names.forEachworks becauseArrayList[String]fixesE, whilestream.map(fn(...) => ...)needsstream.map[String](...)because only the lambda would say whatRis. - A function value whose type says
throws Errorcan't cross into Java, because Java can't see the clause (SPR-TYPE-CALLABLE-THROWS). Handle the error inside a named function and pass a lambda that calls it.
A varargs parameter (String...) takes the trailing arguments, zero or more, which the compiler packs into the array; an opaque Java array of exactly that class is passed through as it is. Fixed-arity overloads are tried first. Path.of("etc", "sprig"), Files.exists(path), String.format(...) and String.join(...) all work this way. Only a type-variable element (T..., as in Arrays.asList) is still rejected.
Look it up before you write it
Before writing code against a Java class, ask sprig api how Sprig sees it. It lists each member's Sprig signature, whether you can use it and, if not, why. With --json, that information is in fields such as interopLevel, interopReasonCodes and adaptation:
sprig api java.time.LocalDate --member parse
sprig api com.example.Client --classpath lib/client.jar --jsonWant to extend a Java class and override a protected method, like next of java.util.Random? It isn't in the public lists; sprig api java.util.Random --member next shows it under protectedMethods. Override it with the same signature in a class declared with conform C to Random(seed) as parent, and call the inherited version as parent.next(bits).
If you use a Java class a lot, sprig wrap can generate a Sprig wrapper file for it. The result is ordinary source code that you're free to edit:
sprig wrap com.example.Client --out src/client.spr --classpath lib/client.jarBefore writing the file, wrap checks the generated code against the same classpath. It won't overwrite an existing file unless you pass --force. The wrapper generator reference has the full rules.
Deprecated Java APIs
When a Java library marks something @Deprecated, Sprig tells you where your code uses it. This program still runs:
import java.util.Date as Date
let date = Date(126, 0, 15)
print(date.getYear() + 1900)2026sprig check and sprig run also print a warning for each use, on standard error:
SPR-JVM-DEPRECATED [TYPE] main.spr:3:12: warning: Calling deprecated Java constructor java.util.Date(int, int, int)
hint: The Java library's documentation names the replacement; 'sprig api CLASS --member NAME' shows which overloads are deprecated.
SPR-JVM-DEPRECATED [TYPE] main.spr:4:12: warning: Calling deprecated Java method java.util.Date.getYear()
2 warning(s); run 'sprig explain <code>' for details on a diagnostic code.- A warning has the code
SPR-JVM-DEPRECATEDand the wordwarning:after the location. It doesn't fail the command: the exit status is still 0, and--jsonreports it with"severity": "warning". - You get one for calling a deprecated constructor or method, reading or writing a deprecated field, overriding a deprecated method in a class that
conforms to a Java class or interface, and importing a deprecated class. - The message names the exact overload, because
URLDecoder.decode(String)is deprecated whiledecode(String, String)is not.(marked for removal)means the library plans to delete it. sprig api java.util.Date --member getYearshows(deprecated: true, forRemoval: false)next to each deprecated member; in--jsonthese are thedeprecatedandforRemovalfields.
Sprig doesn't pick a replacement for you. The library's documentation says what to call instead.
Not supported yet
- Array syntax: there are no array literals, array type annotations, indexing or loops over arrays; arrays can only be passed along.
- Wildcard syntax: a wildcard-typed value can be held and passed on, but you can't write a wildcard in a Sprig declaration, and nothing can be added through
? extends. Deeply nested builder APIs such as Brigadier may still want a small Java adapter; see Fabric mods. - Varargs of a type variable (
T...): there is no element class to pack into. - Java generic inference from the result or a lambda: a method's type parameters are inferred when its arguments fix every one of them exactly (
Collections.sort(names),List.of(1, 2, 3),Objects.requireNonNullElse(a, b)); one that only the result mentions, or that only a lambda would fix, is written (Collectors.toList[Int](),stream.map[String](...)). Java generic types always take written arguments, and there's no variance. A single recursive bound such asT extends Comparable<? super T>is checked on the arguments; intersection bounds (Collections.max) are still rejected. - Nullability defaults without annotations: a library that annotates nothing keeps Sprig's conservative rule, every reference result is
T?; only annotations (run-time visible or read from the class file) and@NullMarked-style defaults change that. - Arithmetic inside Java: an
intoverflow inside a Java method doesn't raise Sprig's numeric error.
The full list is in known limitations.
