Created
December 6, 2017 16:11
-
-
Save gutoccs/4841b985b433f4303321a55ab4d8fd1f to your computer and use it in GitHub Desktop.
Segunda versión para ejecutar código JavaScript (muy simple) en Java. Esta vez se llama a una función en JavaScript desde Java.
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
package javascriptenjava_2; | |
import javax.script.Invocable; | |
import javax.script.ScriptEngine; | |
import javax.script.ScriptEngineManager; | |
import javax.script.ScriptException; | |
/** | |
* @author gutoccs | |
*/ | |
public class JavaScriptEnJava_2 { | |
public static void main(String[] args){ | |
ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); | |
ScriptEngine javaScript = scriptEngineManager.getEngineByName("JavaScript"); | |
String funcionJavaScript = "function suma(a, b) { var suma = Number(a) + Number(b); print('La suma es: ' + suma); }"; | |
try { | |
javaScript.eval(funcionJavaScript); | |
Invocable invocable = (Invocable) javaScript; | |
invocable.invokeFunction("suma", "2", "3"); | |
} catch (ScriptException excepcion1) { | |
System.out.println("Error: "+excepcion1); //Excepción de .eval | |
} catch (NoSuchMethodException excepcion2) { | |
System.out.println("Error: "+excepcion2); //Excepción de .invokeFunction | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Código usado en mi Blog gutoccs.wordpress.com para el artículo Ejecutando JavaScript en Java parte 2.