// 调用内部脚本执行 engine eval(titlescript) // 转换为Invocable Invocable invocableEngine = (Invocable) engine // 不带参数调用sayTitle方法 invocableEngine invokeFunction( sayTitle ) // 调用外部脚本执行 // 创建JS文件的File对象 并读入流 File functionscript = new File( ajava js ) Reader reader = new FileReader(functionscript) // 开始执行ajava js里的程序 engine eval(reader) // 不带参数调用sayHello方法 invocableEngine invokeFunction( sayHello ) // 带参数调用sayHello方法 invocableEngine invokeFunction( sayHello mark ) } catch (Exception e) { e printStackTrace() } } } ajava js文件 function sayHello(){ sayHello(null) } function sayHello(name){ if(name==null){ println( 欢迎你!请注册Ajava会员 ) }else{ println(name+ 独立JAVA社区欢迎你 ) } } 运行结果(控制台) 源码实例 使用javax script调用JS脚本里的方法 lishixinzhi/Article/program/Java/hx/201311/26436
js代码如下:
[javascript] view plain copy
function formula(var1,var2){
return var1+var2-factor
}
java代码如下:
[java] view plain copy
import java.io.FileNotFoundException
import java.io.FileReader
import java.util.Scanner
import javax.script.Bindings
import javax.script.Invocable
import javax.script.ScriptContext
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import javax.script.ScriptException
public class AboutJavaScript {
public static void main(String[] args) throws Exception {
ScriptEngine engine=new ScriptEngineManager().getEngineByName("javascript")
Bindings bind = engine.createBindings()
bind.put("factor", 1)
engine.setBindings(bind, ScriptContext.ENGINE_SCOPE)
Scanner input=new Scanner(System.in)
while (input.hasNextInt()) {
int first= input.nextInt()
int sec=input.nextInt()
System.out.println("输入参数是:"+first+","+sec)
engine.eval(new FileReader("F:/model.js"))
if(engine instanceof Invocable){
Invocable in =(Invocable) engine
Double result=(Double) in.invokeFunction("formula", first,sec)
System.out.println("运行结果:"+result.intValue())
}
}
}
}