| « | November 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 | | | | | | | |
| 公告 |
戒除浮躁,读好书,交益友 |
| Blog信息 |
|
blog名称:邢红瑞的blog 日志总数:523 评论数量:1142 留言数量:0 访问次数:9739148 建立时间:2004年12月20日 |

| |
|
[脚本语言]java里面使用javascript(三):使用java的interface 原创空间, 软件技术, 电脑与网络
邢红瑞 发表于 2006/5/22 18:15:09 |
|
在java代码中还可实现java的interfacepackage test;
/** * * @author hongrui xing */import javax.script.*;public class RunnableImpl { 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 run() { println('run called'); }";
// evaluate script engine.eval(script);
Invocable inv = (Invocable) engine;
// get Runnable interface object from engine. This interface methods // are implemented by script functions with the matching name. Runnable r = inv.getInterface(Runnable.class);
// start a new thread that runs the script implemented // runnable interface Thread th = new Thread(r); th.start(); }}使用OOP机制package test;
/** * * @author hongrui xing */import javax.script.*;public class RunnableImplObject { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String String script = "var obj = new Object(); obj.run = function() { println('run method called'); }";
// evaluate script engine.eval(script);
// get script object on which we want to implement the interface with Object obj = engine.get("obj");
Invocable inv = (Invocable) engine;
// get Runnable interface object from engine. This interface methods // are implemented by script methods of object 'obj' Runnable r = inv.getInterface(obj, Runnable.class);
// start a new thread that runs the script implemented // runnable interface Thread th = new Thread(r); th.start(); }} |
|
|