This is my query...

List<Opportunity> opportunities = Database.query('SELECT OwnerId, Amount, Probability, ExpectedRevenue ' +  mycustomatt + ' FROM OPPORTUNITY ' + ' where isClosed = false');

mycustomatt is a String that is determine at runtime.

If I iterate over the opportunities, how can I get the value for mycustomatt?

for (Opportunity opportunity: opportunities) {
    // can get amount by doing
    System.debug('amount=' + opportunity.Amount);
    // ??? But how do I get the values for my customatt
    // ???



1 Answer 1


Since the other question relates technically to updating and not retrieving I'll give an answer here as well, as well as a security nod. Though in general its pretty much the same principle and area of Apex you need to understand. That being Dynamic Apex and also the methods described on the SObject class, specifically in your case the 'get' methods. In short the following will give you what you want.


If your custom attribute was of type String, you would cast it as follows...

String mycustomattValue = (String) opportunity.get(mycustomatt);

NOTE: You also need to keep in mind SOQL Injection considerations, as described here. Even if your code is providing the additional SOQL query information (as apposed to some end user prompt or config), its usually good practice to follow the recommendations here, just in case the situation changes in your code in the future.

You must log in to answer this question.

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