2016-03-08 31 views
2

我有許多具有不同度量標準的對象。我正在建立一個基於用戶輸入的公式。基於用戶輸入的動態公式

class Object{ 
    double metrics1; 
    double metrics2; 
    .. double metricsN; //number of metrics is knowned 
    } 

用戶可以輸入

 formula=metrics1 

 formula=(metrics1+metrics2)/metrics3 

我已經有一個解析器來解析式,但不知如何存儲該表達式爲進一步的計算

我想避免一次又一次地解析公式爲每一個對象(我最多可以有幾十萬)

+0

你可以把你的整個代碼?我想,那麼每個人都會更容易理解你在問什麼,在這種情況下,你會得到更好的答案。 –

+0

@PritamBanerjee:到目前爲止,我有一個函數 解析表達式並替換obj的度量值的void parse(Object obj,String expr) ,但這需要解析每個對象的expr。解析器從Boann的這個問題中得到答案: http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – Zellint

回答

0

使用ScriptEngine和像這樣的反射。

static class Evaluator { 
    ScriptEngine engine = new ScriptEngineManager() 
     .getEngineByExtension("js"); 

    void formula(String formula) { 
     try { 
      engine.eval("function foo() { return " + formula + "; }"); 
     } catch (ScriptException e) { 
      e.printStackTrace(); 
     } 
    } 

    Object eval(Object values) 
      throws ScriptException, 
       IllegalArgumentException, 
       IllegalAccessException { 
     for (Field f : values.getClass().getFields()) 
      engine.put(f.getName(), f.get(values)); 
     return engine.eval("foo()"); 
    } 

} 

public static class Object1 { 
    public double metrics1; 
    public double metrics2; 
    Object1(double metrics1, double metrics2) { 
     this.metrics1 = metrics1; 
     this.metrics2 = metrics2; 
    } 
} 

public static void main(String[] args) 
    throws ScriptException, 
     IllegalArgumentException, 
     IllegalAccessException { 
    Evaluator e = new Evaluator(); 
    e.formula("metrics1 + metrics2"); 
    Object1 object = new Object1(1.0, 2.0); 
    System.out.println(e.eval(object)); 
    // -> 3.0 
}