import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ExpressTest {

	public static void test1() throws ScriptException {
		String str = "(a >= 0 && a <= 5)";
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("js");
		engine.put("a", 4);
		Object result = engine.eval(str);
		System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
	}
	
	public static void test2() throws ScriptException {
		String str = "43*(2 + 1.4)+2*32/(3-2.1)";
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("js");
		Object result = engine.eval(str);
		System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
	}
	
	public static void main(String[] args) throws ScriptException {
		test1();
		test2();
	}
}


jdk1.6中可以直接这样用
jdk1.5中需要以下jar:commons-logging-1.1.1.jar, js.jar, bsf-all-3.0.jar

posted on 2019-07-17 16:09  无爱无伤  阅读(2887)  评论(0编辑  收藏  举报