search

Home  >  Q&A  >  body text

javascript - How to call methods in js in java?

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

天蓬老师天蓬老师2726 days ago1282

reply all(3)I'll reply

  • 为情所困

    为情所困2017-07-05 10:28:55

    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

    reply
    0
  • 天蓬老师

    天蓬老师2017-07-05 10:28:55

    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.

    reply
    0
  • 怪我咯

    怪我咯2017-07-05 10:28:55

    No
    java is a back-end language, js is a front-end language, and js code cannot be adjusted in java

    reply
    0
  • Cancelreply