« | August 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | | | | | |
| 公告 |
戒除浮躁,读好书,交益友 |
Blog信息 |
blog名称:邢红瑞的blog 日志总数:523 评论数量:1142 留言数量:0 访问次数:9693631 建立时间:2004年12月20日 |

| |
[脚本语言]java里面使用javascript(二):调用函数和方法 原创空间, 软件技术, 电脑与网络
邢红瑞 发表于 2006/5/22 18:06:01 |
在java代码中还可调用javascript函数和方法调用函数package test;
/** * * @author hongrui xing */import javax.script.*;
public class InvokeScriptFunction { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String String script = "function hello(name) { print('Hello, ' + name); }"; // evaluate script engine.eval(script);
// javax.script.Invocable is an optional interface. // Check whether your script engine implements or not! // Note that the JavaScript engine implements Invocable interface. Invocable inv = (Invocable) engine;
// invoke the global function named "hello" inv.invokeFunction("hello", "邢红瑞!!" ); }}使用OOP机制,调用并得到返回值package test;
/** * * @author hongrui xing */import javax.script.*;
public class InvokeScriptMethod { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String. This code defines a script object 'obj' // with one method called 'hello'. String script = "var obj = new Object(); obj.hello = function(name) { return name+'红瑞'; }"; // evaluate script engine.eval(script);
// javax.script.Invocable is an optional interface. // Check whether your script engine implements or not! // Note that the JavaScript engine implements Invocable interface. Invocable inv = (Invocable) engine;
// get script object on which we want to call the method Object obj = engine.get("obj");
// invoke the method named "hello" on the script object "obj" Object ob=inv.invokeMethod(obj, "hello", "hello" ); System.err.println(ob); }} |
|
|