Rhino Java Features
Rhino allows Java classes and objects to be used from JavaScript.
Including | Such as |
---|---|
The Java standard library | java.net.http.HttpClient |
Libraries used by Minecraft | org.apache.commons.io.FileUtils |
Other mods, and libraries used by them | net.fabricmc.api.ModInitializer |
Minecraft internals | net.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.
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:
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.
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.