Created
February 17, 2017 09:34
-
-
Save serge1/3d0b8294f72268edd7849732e716c90f to your computer and use it in GitHub Desktop.
Using JavaScript from Java class (and vice versa)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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