2

I have many objects with different metrics. I am building a formula based on the user input.

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

Users can input

     formula=metrics1

or

     formula=(metrics1+metrics2)/metrics3

I already have a parser to parse the formula, but I do not know how to store this expression for further calculation.

I want to avoid parsing the formula again and again for every single object (I can have up to a few hundred thousands).

Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
Zellint
  • 99
  • 1
  • 6
  • Can you please put your entire code ? I guess then it will be easier for everyone to understand what you are asking and in that case there would be a better chance of you getting an answer. – Pritam Banerjee Mar 08 '16 at 03:44
  • @PritamBanerjee : so far I have a function void parse(Object obj, String expr) that parses the expression and substitute obj's metrics value, but this requires parsing the expr for every object. The parser is taken from Boann 's answer in this questions: http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – Zellint Mar 08 '16 at 06:41

1 Answers1

1

Use ScriptEngine and reflection like this.

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
}