Dynamic variable names in APEX?

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.


I do not believe this is directly possible, however using a map of the variables to a String you would be able to check for a specific variable name and produce the effect shown in your example.

Map<String,String> varNameToValueMap = new Map<String,String>();
varNameToValueMap.put('a','Apple');
varNameToValueMap.put('b','Orange');

String varname = 'a';

Then you could execute the if statement shown in your question as follows.

if(varNameToValueMap.get(varname) == 'Apple')

You can do this with a Map type. It's the Apex equivalent of a PHP associative array.

String varname = 'a';

Map<String,String> vars = new Map<String,String>{
    'a' => 'Apple',
    'b' => 'Orange',
};

if (vars.get(varname) == 'Apple') {
    //
}

Tags:

Apex