I have a java application with a method (A) which should use a javascript function (B), evaluated with rhino, to change some objects before returning them with A. The point is, that the parameter passed from within A to B are complex (List) and also the returned type from B should be from the same type. Currently I have no idea how to use my own classes in the javascript function. Who do I import them in JavaScript?
I use rhino how to call js function from java to load and run my javascript function.
Thanks in advance!
See example. It uses jsr223, but you will get the idea. I am passing list with one instance of MyClass to rhino, it modifies it (via java method call) and finally adds yet another element to list.
package lv.test;
import java.util.ArrayList;
import java.util.List;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class MyClass {
private int field;
public int getField() {
return field;
}
public void setField(final int field) {
this.field = field;
}
public String toString() {
return String.format("{%d}", field);
}
public static void main(String[] args) throws ScriptException {
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine e = manager.getEngineByName("js");
final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE);
final List<MyClass> somelist = new ArrayList<MyClass>();
somelist.add(new MyClass());
b.put("somelist", somelist);
final StringBuilder script = new StringBuilder()
.append("function abc(x,y) { return x+y+new java.lang.Integer(2).intValue(); }")
.append("somelist.get(0).setField(abc(2,3));")
.append("somelist.add(new Packages.lv.test.MyClass()); somelist.get(1).setField(888);");
e.eval(script.toString());
System.out.println(somelist); // [{7}, {888}]
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.