質問

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?

役に立ちましたか?

解決

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.

他のヒント

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.

  1. Throw a deliberate exception at the end of the execute and include the response. Kevin covers this approach in EVAL() in Apex. Secure Dynamic Code Evaluation on the Salesforce1 Platform.
  2. I used a variation of this approach but returned the response via the debug log rather than an intentional exception. See Adding Eval() support to Apex.

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.

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');

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top