Java 调用 Javascript 函数的范例

在Java 7 以后,可以在Java代码中调用javascript中的函数,请看下面的例子:

package com.lee;

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;

/**
 *
 * @author liyanxue
 */
public class JavaInvokeJS {

    public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript" );
        Bindings bind = engine.createBindings();
        bind.put( "factor", 0);
        engine.setBindings(bind, ScriptContext. ENGINE_SCOPE);

        // 输入方式
        /*
         Scanner input = new Scanner(System.in);
         while (input.hasNextInt()) {
         int first = input.nextInt();
         int second = input.nextInt();

         System.out.println("输入的参数是:" + first + ", " + second);
         engine.eval(new FileReader("/Users/ liyanxue/model.js"));

         if (engine instanceof Invocable ) {
         Invocable in = (Invocable ) engine;
         // 执行 js函数
         Double result = (Double) in.invokeFunction("formula", first, second);
         System.out.println("运算结果是:" + result.intValue());
         }
         }
         */
        int first = 23;
        int second = 7;

        System. out.println("输入的参数是:" + first + ", " + second);
        engine.eval( new FileReader("/Users/liyanxue/model.js" ));

        if (engine instanceof Invocable) {
            Invocable in = (Invocable) engine;
            // 执行js函数
            Double result = (Double) in.invokeFunction( "formula", first, second);
            System. out.println("运算结果是:" + result.intValue());
        }
    }
} 

/Users/liyanxue/model.js里的代码:

function formula(var1, var2) {
     return var1 + var2 + factor;
} 
原文地址:https://www.cnblogs.com/IcanFixIt/p/4764380.html