Dynamic variable names in APEX?

Given 3 variables:

String a = 'Apple';
String b = 'Orange';
String varname = 'a';

Is there a way that I can use varname as a link to the variable a in my code such that the following would evaluate to true?:

if (Var(varname)=='Apple')

I know that there are ways to do it in some scripting languages such as PHP but have been unable to find any mention of this in Apex searching the web.

The PHP equivalent of what I’m after appears to be $($varname).


No. Apex is a compiled language, what you’re describing are variable variables typically found in languages that are parsed (interpreted) at runtime (let’s not dig into opcodes, Zend’s virtual machine, Facebook’s HipHop etc).

Apex can be pretty flexible when executing queries from strings (but compiled query performs faster) and there are ways to do something like SELECT * FROM Account and access all fields on the object.

Search the documentation for “dynamic Apex” but the bottom line is that the code has to be compiled before it’s executed. Maybe if you’d write more about your requirements (like accessing all name-value parts in URL?) we’d be able to assist more.

You can also try to use the API to fire off ExecuteAnonymous calls (code snippets that are run and discarded, they won’t be saved as new class for example) but that’s getting bit hardcore…

There’s Type class that lets you instantiate variables in dynamic way – but you still have to specify the variable name at compile-time. There’s instanceof operator, interfaces, How to invoke a method of an apex class at run time… lots of options to “do it right”.

Edit: I forgot about 1 more hack: JSON.deserialize* methods. They come in few flavours… But even then you have to dump them into “some named variable” and (in the example without expected type definition) access as the Map example from other answers. So at best you’d be getting a map with many interesting properties. If you’re interested in bit more complex example of casting – check out https://stackoverflow.com/questions/3122038/how-do-i-integrate-salesforce-with-google-maps, I’m pretty happy how that one turned out.

Source : Link , Question Author : Venko , Answer Author : Community

Leave a Comment