Public String var='public String var1=\'Some text\'; ' ;

I require this string inside var to execute and create a variable "Var1" and assigned with the value "Some text".

Is it possible to do this? If Yes then how will it be possible?

  • I'm quite(99%) sure that it's not possible. Why would you want it anyway?
    – Novarg
    Nov 27, 2014 at 9:04
  • 1
    While it is possible using the execute anonymous method below, you should be aware of the security risk. If you build the Apex from any kind of user or external system input then there is always the possibility of malicious code being executed if you don't fully validate the input.
    – Mark Keats
    Nov 27, 2014 at 10:10

2 Answers 2


Not sure that you can do it directly like this - but the question is why you would want to execute in this fashion. I would guess that you may not know either the type or assignment at runtime - in that case I would look into using reflection.

Here's a good article on using reflection to achieve possibly what you are looking for: http://www.sundoginteractive.com/sunblog/posts/using-reflection-with-salesforce-custom-apex-classes-sort-of


The closest thing you'll get to run APEX as a string is Execute Anonymous - which doesn't help you. The EA will operate in a separated context and you can't interact with variables between contexts and you need an API call to invoke it. What EA is good for are CRUD operations.

You must log in to answer this question.

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