Below is a piece of code I am trying to run.

global  class TriggerClass {

    @future (callout=true)
    public static void ifMethod(String sessionId, String ifcondition) {
        ToolingAPI.SforceService x = new ToolingAPI.SforceService();
        x.SessionHeader = new ToolingAPI.SessionHeader_element();
        x.SessionHeader.sessionId = UserInfo.getSessionId();
        x.SessionHeader.sessionId = sessionId;
        System.debug('inside myMethod...'); 
        Integer a;
        System.debug('Result of if-------------' +ifcondition);
        System.debug('Result of a-----------------'+a);
        System.debug('exiting myMethod...'); 

Inside the x.executeAnonymous statement, I want to write code which executes when the if condition evaluates to true and also I want a else condition.My ifcondition contains a string something like "if(22>21 && 8000<9000)".

  • 2
    See Daniel Ballinger's Adding Eval() support to Apex. Personally, I would write an expression parser in Apex instead - there are answers somewhere on this forum about that but AFAIK there is no first-class implementation posted. – Keith C Mar 24 '16 at 8:44

There is no native JavaScript like eval() statement in Apex. As you have started down in your question, you can use anonymous Apex via the API methods to execute arbitrary code from a string. The challenge then becomes, how do you get the results of the execution back into the current context.

Anonymous Apex doesn't have native support for returning a result. Any variables you modify in the anonymous Apex won't exist in the calling context. So in your case, your Interger a will still be null.

Instead you can coerce one of the available mechanisms that anonymous Apex provides to get the results back.

One option is to use an exception in the anonymous Apex to send the result back. You can see an example of this implementation in Kevin's EVAL() IN APEX. SECURE DYNAMIC CODE EVALUATION ON THE SALESFORCE1 PLATFORM post. You then need to parse the results out of the resulting fault message.

The other alternative is to capture a debug log. This is easier using the Apex API, as it will return the log directly on the API call. I've covered this in my post Adding Eval() support to Apex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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