java調用js,js中調用java__js

來源:互聯網
上載者:User

 

 

1)使用指令碼語言的優勢

Rapid turnaround, encouraging experimentation.

Changing the behavior of a running program.

Enabling customization by program users.

 

2)

The site http://scripting.dev.java.net provides engines for a wide range of scripting languages.

 For example, to add support for Groovy, the class path should contain groovy/lib/* 

 (from http://groovy.codehaus.org) and groovy-engine.jar (from http://scripting.dev.java.net).

 

3)

javax.script.ScriptEngineManager

javax.script.ScriptEngineFactory

javax.script.ScriptEngine

javax.script.Invocable 

javax.script.CompiledScript

 

ScriptEngine engine = manager.getEngineByName("JavaScript");

 

Object result = engine.eval(scriptString);

Object result = engine.eval(reader);

engine.put(k, 1728);

Object result = engine.eval("k + 1");

 

4)重新導向Input和Output

StringWriter writer = new StringWriter();

engine.getContext().setWriter(new PrintWriter(writer, true));

 

5)Calling Scripting Functions and Methods

 

To call a function, call the invokeFunction method with the function name, followed by the function parameters:

 

if (engine implements Invocable)

   ((Invocable) engine).invokeFunction("aFunction", param1, param2);

 

 

If the scripting language is object oriented, you call can a method like this:

 

Code View:

((Invocable) engine).invokeMethod(implicitParam, "aMethod", explicitParam1, explicitParam2);

 

 

 

6)Compiling a Script

Reader reader = new FileReader("myscript.js");

CompiledScript script = null;

if (engine implements Compilable)

   CompiledScript script = ((Compilable) engine).compile(reader);

 

if (script != null)

   script.eval();

else

   engine.eval(reader);

7)

在 http://www.mozilla.org/rhino/ 下載rhino:

把js.jar加入系統CLASSPATH中

可以以互動模式調用js解譯器:

java org.mozilla.javascript.tools.shell.Main

java org.mozilla.javascript.tools.debugger.Main

 

8)相互調用

HelloWorld hello = new HelloWorld();

engine.put("script_hello", hello);

engine.eval("script_hello.sayHello()");

 

String script = "function say(first,second){ print(first +' '+ second+'//n'); }";

engine.eval(script);

Invocable inv = (Invocable) engine;

inv.invokeFunction("say", "Hello", "Tony");

script = "function max(first,second) "

+ "{ return (first > second) ?first:second;}";

engine.eval(script);

  //js與java介面的調用

Object obj = inv.invokeFunction("max", "1", "0");

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.