I am creating dynamic code so I am creating a string that I would like to use as the expression inside an if statement.

if (string) {


The string that i have created will have to act as the "literal code". Does anyone know of a way to do this?

  • There is no equivalent of like an eval statement. There is probably a way to get to end result, but I would need more info on what you are trying to do.
    – CyberJus
    Apr 3, 2015 at 19:03

4 Answers 4


It is true that there is no substitute for eval() in APEX however there does exist a workaround. The workaround is to prepare a string and execute it as "anonymous block" and parse the results.

Check this blog post which shows how this could be achieved http://codefriar.com/2014/10/30/eval-in-apex-secure-dynamic-code-evaluation-on-the-salesforce1-platform/


I have restructured my project so that I will b able to avoid this type of problem. I will not be able to run the expression when i pull the data from the SOQL. Thank you for the answers

  • Would you be able to share how exactely you solved this ? That may help others in the future! Apr 24, 2015 at 7:31
  • Sure! In a Visualforce page I give a user a picklist that contains objects. Based on which objects they choose, then can then choose one of that object's corresponding fields. Based on the field chosen, they will then be presented with possible operators and they enter the value. I will use this information to evaluation if the expression is true. In the backend, I will do SOQL against each object and store the information. Then i loop through the expressions and will evaluate from there.
    – Tyager
    Apr 25, 2015 at 15:22

If statements evaluate boolean expressions, which can be stored as a boolean value and passed on to the if statement through a variable.

An example method:

public doSTuff(List<object>data, boolean condition){
         //do stuff to data

//somewhere else
 List<sobject> = [SOQL..]; //dummy code
boolean condition =  param1 > data.size(); //dummy boolean expression
doStuff(data,condition); //passing your boolean expression to the method

//somewhere else 2
List<sobject> = [SOQL..]; //dummy code
boolean condition =  param1 <= data.size(); //different boolean expression
doStuff(data,condition); //same method!

You can not do this in apex, but in javascript, you can use 'eval' method to execute literal code. As an alternative, you can pass literal code to javascript, then run it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .