Question

My expression is like this : ($a+$b)/$c

String expr = "($a+$b)/$c";
Float sum = Float.valueOf("2.2");
HashMap<String, Float> valueMap =  new HashMap<String,Float>();
valueMap.put("$".concat(a)), sum);
sum = sum + Float.valueOf("1");
valueMap.put("$".concat(b)), sum );
sum = sum + Float.valueOf("1");
valueMap.put("$".concat(c)), sum );
VariableResolverFactory myVarFactory = new MapVariableResolverFactory();

Serializable compileExpression = MVEL.compileExpression(mtrExprD, valueMap); // here,     Only a map of < String,Object > is allowed.

MVEL.executeExpression(compileExpression, myVarFactory); // This should return me a float Value.

MVEL.executeExpression() returns an Object ; I want myExpression to return a float value instead of an Object. How to solve this?

Était-ce utile?

La solution

Mvel always return the object, we need to check the instanceOf for say Boolean, Float etc. Also while doing calculation using arithmetic operators , be on a safer side to use null safe values.

for eg, if

your exp is a * b, and if a or b is null, then Mvel gives result as false.

Autres conseils

MVEL#executeExpression  return the Object

You have to cast it in Float

Float result = (Float) MVEL.executeExpression(compileExpression, myVarFactory);

like this

Serializable  compiled = MVEL.compileExpression("x * y"); 
Map<String, Integer> vars = new HashMap<>();
    vars.put("x", new Integer(5));
    vars.put("y", new Integer(10));
    // Executes the compiled expression
Integer result = (Integer) MVEL.executeExpression(compiled, vars); 

See Mvel doc

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top