java调用js,js中调用java

 

 

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");

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值