How to call methods in js in java
// js 代码 STRING_UTIL = {}; STRING_UTIL.isNotEmpty = function (str){ return "" != str; }
// java 代码 Reader scriptReaderB = new InputStreamReader( new FileInputStream( new File("F:\tech-study\js-comm\release\bundle.js")),"utf-8"); engine.eval(scriptReaderB); // engine.eval(scriptReaderA); if (engine instanceof Invocable) { // 调用JS方法 Invocable invocable = (Invocable)engine; Object result = invocable.invokeFunction("STRING_UTIL.isNotEmpty", new Object[]{"hahaha"}); System.out.println(result.toString()); } // 调用异常 java.lang.NoSuchMethodException: no such method: STRING_UTIL.isNotEmpty at com.sun.script.javascript.RhinoScriptEngine.invoke(RhinoScriptEngine.java:286) at com.sun.script.javascript.RhinoScriptEngine.invokeFunction(RhinoScriptEngine.java:258) at AAAAAAA.main(AAAAAAA.java:29) // 如果在添加一个全局函数 function isNotEmpty (str){ return STRING_UTIL.isNotEmpty(str); }
Change the calling method to
Object result = invocable.invokeFunction("isNotEmpty", new Object[]{"hahaha"});
This is a successful operation
After your own implementation, you can use two methods to achieve it:
Use engine.eval
Object result = engine.eval("STRING_UTIL.isNotEmpty('" + str + "')"); to call.
Use the invokeMethod method to implement
First get the object
Object thiz = engine.get("STRING_UTIL");
Next, call the method according to the object
Object result = invocable.invokeMethod(thiz, "isNotEmpty", new Object[]{"hahaha"});
Introducing another book to everyone: "In-depth Understanding of Java 7: Core Technologies and Best Practices"
The second chapter here is very detailed. If you want to go, you can take a look
invokeFunction method description The first parameter is the method name, the following parameters are all method parameters, and the return value is object.
No
java is a back-end language, js is a front-end language, and js code cannot be adjusted in java