利用java 6.0的脚本引擎执行字符串表达式运算

阅读更多

例子都在这里了:http://www.java2s.com/Code/Java/JDK-6/Script-Engines.htm,以下是个小测试:

package com.spell.script.engine;

import java.util.List;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptsTest {

    public static void main(String[] args) throws ScriptException {
        ScriptsTest.list();
        ScriptsTest.runScript("(1+2+3)*2/0.5");
        ScriptsTest.runScript("print ('not a math script')");
        ScriptsTest.valueBind();

    }

    public static void list() {
        // create ScriptEngineManager
        ScriptEngineManager manager = new ScriptEngineManager();
        List factoryList = manager.getEngineFactories();
        for (ScriptEngineFactory factory : factoryList) {
            System.out.println(factory.getEngineName());
            System.out.println(factory.getEngineVersion());
            System.out.println(factory.getLanguageName());
            System.out.println(factory.getLanguageVersion());
            System.out.println(factory.getExtensions());
            System.out.println(factory.getMimeTypes());
            System.out.println(factory.getNames());
        }
    }

    public static void runScript(String script) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        try {
            System.out.println(engine.eval(script));
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

    public static void valueBind() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        engine.put("a", 1);
        engine.put("b", 5);

        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        Object a = bindings.get("a");
        Object b = bindings.get("b");
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        Object result = engine.eval("c = a + b;");
        System.out.println("a + b = " + result);
    }
}

 

原文:http://hi.baidu.com/ecspell/item/8731e0df10a5a7e4785daaae

 

你可能感兴趣的:(利用java 6.0的脚本引擎执行字符串表达式运算)