Boolean b1 = true;
Boolean b2 = true;
String b3 = 'b1 && b2';
Boolean b4 = Boolean.valueOf(b3);
system.debug('test Bool '+ b4);
Given a string how can you convert into expression without breaking the sting.
Boolean b1 = true;
Boolean b2 = true;
String b3 = 'b1 && b2';
Boolean b4 = Boolean.valueOf(b3);
system.debug('test Bool '+ b4);
Given a string how can you convert into expression without breaking the sting.
It is possible to mimic a Javascript eval() in Apex by making a callout to the executeAnonymous API method.
There are two common ways you can get a response back from executeAnonymous.
Using my example the Apex would be something like:
string toEval =
'Boolean b1 = true;' +
'Boolean b2 = true;' +
'boolean b3 = b1 && b2;' +
'System.debug(LoggingLevel.Error, b3);';
boolean b4 = soapSforceCom200608Apex.evalBoolean( toEval );
system.debug('test Bool '+ b4);
I think what you're after doing is creating an expression as a string and then evaluating it and obtaining the result in Apex.
I don't think it is actually possible to evaluate expressions in Apex natively (it would be great if it was, I also wondered the same since we have the Formula functions). I think the best you could do is roll your own expression parser and AND(Boolean, Boolean) function that implements the required behaviour.
I created an apex class on github to do this. Take a look at this... https://github.com/hsaraujo/BooleanEvaluate-Apex
List<Boolean> values = new List<Boolean>{
true, false, true, true, false, true, true, true
};
BooleanEvaluate boolEval = new BooleanEvaluate('1 && ( ( 2 || 3 ) && 6 ) && ( 4 && 5 || ( 7 && 8 ) )', values);
boolEval.evaluate();
If someone wants to improve it, please fork! Hope it helps
Also you can try Script.apex(https://github.com/Click-to-Cloud/Script.apex)
Map context = new Map{ b1 => true, b2 => false };
Boolean result = (Boolean)ScriptEngine.getInstance().eval('b1 && b2', context);