In case you can’t make your class Point extends class PVector, or even prefer not to, you can instead code your function under Java’s built-in JavaScript engine called Nashorn! ![]()
This way, you’ll be able to pass an object of any datatype to that JS function, as long as that object got all of the members your function expects to find in it. ![]()
I’ve re-written the previous Java Comparator ASCENT_X:
static final Comparator<PVector> ASCENT_X = new Comparator<PVector>() {
@Override final int compare(final PVector v1, final PVector v2) {
return (int) Math.signum(v1.x - v2.x);
}
};
in Nashorn JS syntax now: ![]()
final Comparator ASCENT_X = (Comparator) runJS(compileJS(js,
"new java.util.Comparator() {",
" compare: function (obj1, obj2) {",
" return obj1.x - obj2.x;",
" }",
"};"));
Here’s the whole sketch, which is now able to sort() any object datatype which got field x in it, bypassing Java’s strict datatype system: ![]()
/**
* JS Nashorn Comparator (v1.2)
* GoToLoop (2018/Sep/10)
* Discourse.Processing.org/t/accessing-functions-from-java-generics/3391/14
*/
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.CompiledScript;
import javax.script.Compilable;
import java.util.Comparator;
import java.util.Arrays;
//import java.util.Collections;
final ScriptEngine js = new ScriptEngineManager().getEngineByName("Nashorn");
final Comparator ASCENT_X = (Comparator) runJS(compileJS(js,
"new java.util.Comparator {",
" compare: function (obj1, obj2) obj1.x - obj2.x",
"};"));
final PVector[] vecs = {
PVector.random2D(this).mult(100),
PVector.random2D(this).mult(100),
PVector.random2D(this).mult(100)
};
final MyVec[] myVecs = { new MyVec(), new MyVec(), new MyVec() };
public class MyVec {
public float x = random(-100, 100), y = random(-100, 100), z;
@Override String toString() {
return "[ " + x + ", " + y + ", " + z + " ]";
}
}
void setup() {
println(ASCENT_X, ENTER);
println(vecs);
Arrays.sort(vecs, ASCENT_X);
println(vecs);
println();
println(myVecs);
Arrays.sort(myVecs, ASCENT_X);
println(myVecs);
exit();
}
@SafeVarargs static final CompiledScript compileJS
(final ScriptEngine js, final String... statements) {
final String expression = statements != null?
PApplet.join(statements, PConstants.ENTER) : "";
try {
return ((Compilable) js).compile(expression);
}
catch (final ScriptException cause) {
PApplet.println(cause);
System.err.println(expression);
throw new RuntimeException(cause);
}
}
static final Object runJS
(final CompiledScript compiled) {
try {
return compiled.eval();
}
catch (final ScriptException cause) {
PApplet.println(cause);
throw new RuntimeException(cause);
}
}