Skip to content

Instantly share code, notes, and snippets.

@serge1
Created February 17, 2017 09:34
Show Gist options
  • Save serge1/3d0b8294f72268edd7849732e716c90f to your computer and use it in GitHub Desktop.
Save serge1/3d0b8294f72268edd7849732e716c90f to your computer and use it in GitHub Desktop.
Using JavaScript from Java class (and vice versa)
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptTest {
public final String hello = "Hello";
public String getStr() {
return hello;
}
public static void main(String[] args) {
ScriptEngineManager scriptManager = new ScriptEngineManager();
List<ScriptEngineFactory> listOfFactories = scriptManager.getEngineFactories();
for (ScriptEngineFactory factory : listOfFactories) {
System.out.println(factory.getEngineName() + " " + factory.getLanguageName());
for (String name : factory.getNames()) {
System.out.println( " " + name);
}
}
ScriptEngine scriptEngine = scriptManager.getEngineByName("js");
try {
Integer myInt = (Integer)scriptEngine.eval("2+3");
System.out.println(myInt);
scriptEngine.eval("var Test = Java.type('ScriptTest'); var test = new Test(); var rs = test.getStr(); print(rs)");
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment