亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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

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)  
      {  
          // 調(diào)用JS方法  
          Invocable invocable = (Invocable)engine;  
          Object result = invocable.invokeFunction("STRING_UTIL.isNotEmpty", new Object[]{"hahaha"});
          
          System.out.println(result.toString());

      }
// 調(diào)用異常
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)

// 如果在添加一個全局函數(shù)
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

天蓬老師
天蓬老師

歡迎選擇我的課程,讓我們一起見證您的進(jìn)步~~

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