日期:2014-05-16  浏览次数:20394 次

Java 对 JavaScript 脚本的方法调用
package com.chen.java;

import java.io.File;
import java.io.FileReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import com.chen.interfaces.Greeter;

/**
 * 这个场景的代码用于在web容器中调用js中定义的方法。Greeter 是java接口类,和js中定义的方法在名称,参数和返回值上保持一致
 * @author Administrator
 *
 */
public class TestScript {
    public static void main(String[] args) {
        String url = TestScript.class.getResource("/").getPath();
        String str = null;
        try {
            str = URLDecoder.decode(url.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String path = new File(str).getParent() + File.separator + "js" + File.separator + "test.js";
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            engine.eval(new FileReader(path));
            
            Greeter g = ((Invocable) engine).getInterface(Greeter.class);
            System.out.println("result = " + g.greet("androidla"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


在java中的方法:
package com.chen.interfaces;

public interface Greeter {
    String greet(String whom);
}


在js中定义的方法:
function greet(name) {
	return "I'm write in JavaScript, hello, " + name;
}


运行结果:
result = I'm write in JavaScript, hello, androidla


相关参考: http://www.ibm.com/developerworks/cn/java/j-lo-jse66/index.html