RingJavafor Ring

Your own Java class

Write a Java class, compile it from Ring with the compiler in the JDK, and use it like any other class.

What you will learn#

The program#

samples/UsingJava/tutorials/ch15_own_class.ring
# Tutorial 15: your own Java class - write it, compile it from Ring, and use it
load "java.ring"

using {
	"java.lang"
	"java.nio.file"
}

Files = new Files

# 1. the Java source: a small class with a constructor, a method, a static method and an interface that Ring can implement
cSource = '
package demo;

public class Greeter {
	private final String name;
	public Greeter(String name) { this.name = name; }
	public String greet() { return "Hello, " + name + "!"; }
	public String greet(String other) { return "Hello, " + other + "! I am " + name + "."; }
	public static int twice(int x) { return x * 2; }
	public void repeat(int times, Callback callback) {
		for (int i = 1; i <= times; i++) callback.call(i, name);
	}
	public interface Callback { void call(int i, String name); }
}'

# 2. compile it with the compiler that is inside the JDK (the program needs a JDK, not only a JRE)
oFolder = Files.createTempDirectory(["greeter",[]])
oSourceFolder = oFolder.resolve("demo")
Files.createDirectory(oSourceFolder,[])
oFile = oSourceFolder.resolve("Greeter.java")
Files.writeString([oFile,cSource,[]])
oCompiler = jStatic("javax.tools.ToolProvider","getSystemJavaCompiler",[])       # a JavaCompiler: its Ring class (javax.tools) loads by itself
? "compiler found: " + (not jIsNull(oCompiler))
nResult = oCompiler.run(NULL,NULL,NULL,[ oFile.toString() ])
? "compile result (0 = ok): " + nResult

# 3. the folder of the classes goes to the class path, and the class is a Java class like any other
jClasspath(oFolder.toString())
oGreeter = jNew("demo.Greeter",["Ring"])
? oGreeter.callMethod("greet",[])
? oGreeter.callMethod("greet",["Java"])
? jStatic("demo.Greeter","twice",[21])

# 4. a Ring function as the Callback of the class: the interface is nested, so a text is enough
cLog = ""
oGreeter.callMethod("repeat",[3,jCallback("onCall")])
? cLog

func onCall aArgs
	cLog += "" + aArgs[1] + ":" + aArgs[2] + " "
Output
compiler found: 1
compile result (0 = ok): 0
Hello, Ring!
Hello, Java! I am Ring.
42
1:Ring 2:Ring 3:Ring

How it works#

The program writes the source of a class to a file and compiles it with ToolProvider.getSystemJavaCompiler(): a JDK is needed, not only a JRE. jClasspath adds the folder of the classes, and jNew("demo.Greeter", ["Ring"]) creates an object of the new class like one of any other Java class.

Exercises#

  1. Add a method that takes a list.
  2. Add a second interface and implement it with a Ring function.
  3. Put the compiled class in a jar and load the jar.

Next#

A first window

RingJava - use Java classes and methods from Ring programs.