javascript - How to call methods in js in java?
天蓬老师
天蓬老师 2017-07-05 10:26:55
0
3
1296

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

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
为情所困

After your own implementation, you can use two methods to achieve it:

  1. Use engine.eval
    Object result = engine.eval("STRING_UTIL.isNotEmpty('" + str + "')"); to call.

  2. 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

Peter_Zhu
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine javaScript = manager.getEngineByName("JavaScript");
InputStream stream =
                    JS.class.getResourceAsStream("/js/test.js");
BufferedReader reader =
                    new BufferedReader(new InputStreamReader(stream));
javaScript.eval(reader);
invocable = (Invocable) javaScript;
invocable.invokeFunction("method");

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template