如題
例如:String str = "(a >= 0 && a <= 5)";
如今知道a的值,怎麼知道a是否符合str這個字符串,我知道能夠截字符串,可是真正的業務邏輯串很麻煩,java
正確答案:spa
import javax.script.*; public class TestScript { public static void main(String[] args) throws Exception { 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); } }
jdk1.6中能夠直接這樣用
jdk1.5中須要如下jar:commons-logging-1.1.1.jar , js.jar, bsf-all-3.0.jarcode