0

I am working on a requirement wherein string(as a combination of boolean values) is to be evaluated. eg: '(TRUE && TRUE)'. Boolean.valueof() seems to work only with single stringified boolean eg : boolean.valueof('TRUE'). I was wondering if there is an OOTB way to convert the string to object form and then convert object to boolean. Something like:

String str = '(TRUE && TRUE)';
Object obj = str;
Boolean bool = (Boolean)obj;
1
3

What you're looking to do isn't a simple conversion from String to Boolean, what you're trying to do here is to take a String and execute it as an expression, like Javascript's eval() function.

That's an entirely different beast (than variable casting), and not one that Apex is meant to handle.

There are some similar questions that pop up from time to time, like Is there anyway to execute a string in apex which would be similar to javascript eval() function and Evaluate expressions/conditions in apex code ? (which are stored in string/text)

The gist of the comments and answers on those questions are that this is not something Apex does. If you're adamant about doing this, there are methods, but none are particularly easy or clean.

  • Make a callout from your code to the REST API so you can run your string as anonymous apex
  • Attempt to push this work off to Javscript so you can use its eval() function
  • Build a simple evaluation engine in Apex that can handle things provided in reverse polish notation (i.e. [+, 4, 5], which would result in 9)

Not the answer you're looking for? Browse other questions tagged or ask your own question.