必须jre6才行,要不需要用开源库了
package script;
import javax.script.*;
/**
* Java调用JavaScript示例
*
* @author Birdshover
*
*/
public final class scriptMaster {
/**
* 运行指定脚本
* @return 返回脚本值
*/
public int run() {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine engine = m.getEngineByExtension("js");
try{
engine.eval("var t=1;t++;");
engine.eval("t++;");
}catch(ScriptException ex){
return -1;
}
Float val = Float.parseFloat(engine.get("t").toString());
return val.intValue();
}
}
java调用javascript,而javascript内部又调用了java的类库。
public String now(){
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine engine = m.getEngineByExtension("js");
try{
engine.eval("var t= new java.util.Date();");
}catch(ScriptException ex){
return (new Date()).toString();
}
return engine.get("t").toString();
}