Skip to content

Rhino Java Features

Rhino allows Java classes and objects to be used from JavaScript.

IncludingSuch as
The Java standard libraryjava.net.http.HttpClient
Libraries used by Minecraftorg.apache.commons.io.FileUtils
Other mods, and libraries used by themnet.fabricmc.api.ModInitializer
Minecraft internalsnet.minecraft.client.MinecraftClient

More about accessing Minecraft internals in a bit.

Basic Usage

Java classes are imported from the Package object, for example java.util.ArrayList can be accessed from Packages.java.util.ArrayList.

Example: Reading a File

To read a file using java.nio.file, we use the Files.readString method, which takes a Path as argument.

js
let { Files } = Packages.java.nio.file;
let { FabricLoader } = Packages.net.fabricmc.loader.api;

// .minecraft/config/jscore/
let configRoot = FabricLoader.getInstance().getConfigDir().resolve("jscore");
// .minecraft/config/jscore/modules/fs/README.md
let path = configRoot.resolve("modules/fs/README.md");

let content = Files.readString(path);
console.log(content);

This is equivalent to using fs:

js
let fs = require("fs");

let content = fs.readFileSync("modules/fs/README.md", "utf8");
console.log(content);

Implementing Interfaces

An object that implements an interface can be created if all methods required by the interface are defined.

Example: Listening to an Event

To listen to the START_CLIENT_TICK event, we need to create an object that implements the StartTick interface, which implements a single method onStartTick.

js
let { START_CLIENT_TICK, StartTick } =
  Packages.net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;

let counter = 0;

let listener = new StartTick({
  onStartTick: (client) => {
    counter++;
    console.log(counter);
  },
});

START_CLIENT_TICK.register(listener);

If this code is in init.js, then an additional listener is registered at every restart. You may want to set a value at module.globals to indicate a listener has previously been registered.