Reputation: 23
I've looked into this, and it seems there is no directly related function available since Apex is so strongly typed, but I was wondering if anyone had found a workaround. I'm designing a credit risk object and my client wants to be able to insert expressions such as "150 + 3" instead of "153" when updating fields to help speed things up on her end. Unfortunately, I'm new to salesforce, so I'm having trouble coming up with ideas. Is this even feasible?
Upvotes: 1
Views: 2736
Reputation: 11
Script.apex can help with evaulating javascript expressions. Check this out. https://github.com/Click-to-Cloud/Script.apex. It is just as simple as this.
Integer result = (Integer)ScriptEngine.getInstance().eval('1 + 2');
Upvotes: 0
Reputation: 13537
It is possible to mimic a Javascript eval() in Apex by making a callout to the executeAnonymous API method on either the Tooling or Apex API.
The trick is you need to pass any required input parameters in the eval string body. If a response is required you need a mechanism to extract it.
There are two common ways you can get a response back from executeAnonymous.
Using my example the Apex would be something like:
integer sum = soapSforceCom200608Apex.evalInteger(
'integer result = 150 + 3; System.debug(LoggingLevel.Error, result);');
You might not be able to perform the callout during member initialisation or in a constructor.
Incidentally, the Salesforce Stackexchange site is a great place to ask Salesforce specific questions.
Upvotes: 1
Reputation: 2605
You could allow hand-entering of SOQL statements and then use dynamic SOQL to process them. But this would require a bit more than "150 + 3."
Otherwise you could do this in JavaScript and pass the value back to Apex as an already calculated number.
Upvotes: 1