尝试从java类访问javascript时出错

时间:2015-10-02 19:51:53

标签: javascript java scriptengine

我有一个JavaScript文件,其函数如下所示:

function getid() {
    var e = document.getElementById("identity");
    var iden = e.options[e.selectedIndex].value;    
    return iden;
}

我试图使用以下代码来使用JavaScript:

public ResultSet Getsname() throws ClassNotFoundException, SQLException
{  
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    // read script file
    try {
        engine.eval(Files.newBufferedReader(Paths.get("C:/Users/Sony/workspace/StudentRegiForm/WebContent/ValidateMark.js"), StandardCharsets.UTF_8));
    } catch (ScriptException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Invocable inv = (Invocable) engine;
    // call function from script file
    Integer uid= null;
    try {
        uid = (Integer) inv.invokeFunction("getid()");
    } catch (NoSuchMethodException | ScriptException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

执行时我不断收到此错误:

  

java.lang.NoSuchMethodException:没有这样的函数getid()

1 个答案:

答案 0 :(得分:0)

更改

uid = (Integer) inv.invokeFunction("getid()");

uid = (Integer) inv.invokeFunction("getid");

我会谨慎地投射到Integer以便更好地使用Object然后再做 if (uid instanceof Integer) ...

所以

  Object uid = null

  uid =  inv.invokeFunction("getid");

  if (uid instanceof Integer){
     system.out.println("ok");
  }