java中調用JavaScript進階應用程式(在JavaScript中調用Java中對象的方法)

來源:互聯網
上載者:User

        前面我們已經看到來在java中呼叫指令碼引擎執行JavaScript,現在我們看下將對象綁定到指令碼引擎後,怎麼在JavaScript中調用Java中對象的方法。

使用執行個體如下:

import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.script.Bindings; import javax.script.Invocable; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; /** * * @author zcb */ public class SuperTest { public static void main(String[] args) { ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine se = null; se = sem.getEngineByExtension("js"); //se=sem.getEngineByMimeType("text/javascript"); //se=sem.getEngineByName("javascript"); String jsscript = "function mytest(){" + "println(ContextProperties);" + "ContextProperties.remove('three');" + "println(ContextProperties);" + "println('1:'+ContextProperties.containsKey('one'));" + "println('2:'+ContextProperties.containsKey('four'));" + "println('size:'+ContextProperties.size());" + "println(ContextProperties.get('one'));" + "return (ContextProperties.get('one')>ContextProperties.get('two'))?true:false;}";//也可以調用綁定對象的別的方法,如自訂對象的方法等 Bindings bindings = se.getBindings(ScriptContext.ENGINE_SCOPE); Map map = new HashMap(); map.put("one", 1); map.put("two", 5); map.put("three", 5); // bindings.putAll(map); // System.out.println("one:"+bindings.get("one")); // System.out.println("two:"+bindings.get("two")); //綁定Map對象,也可以綁定自訂的Java對象 bindings.put("ContextProperties",map); try { Object flag = null; se.eval(jsscript, bindings); if (se instanceof Invocable) { Invocable invoke = (Invocable) se; flag = invoke.invokeFunction("mytest"); System.out.println("flag:" + flag); } //輸出經過JavaScript修改後的map對象 System.out.println("map:"+map); } catch (NoSuchMethodException ex) { Logger.getLogger(SuperTest.class.getName()).log(Level.SEVERE, null, ex); } catch (ScriptException ex) { Logger.getLogger(SuperTest.class.getName()).log(Level.SEVERE, null, ex); } } }

輸出結果如下:

{two=5, one=1, three=5}
{two=5, one=1}
1:true
2:false
size:2
1
flag:false
map:{two=5, one=1} 注意:在js中對Java對象的更改也生效來哦~
這樣,我們就實現來Java調用JavaScript,而JavaScript又調用了Java,實現了迴圈調用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.