I have junction object (Junction__c) with two master-detail relationships to 'contacts' and 'Training_Session__c'. I'm trying to write a query to generate a list of email addresses for use in a visual force page. Here's what the APEX class looks like.

   List<SObject> contact_list = [SELECT id, contact__r.email, contact__r.name FROM Junction__c WHERE Training_Seesion__c = :ApexPages.currentPage().getParameters().get('id')];

Mapping the values of a result (getPopulatedfiedldsAsMap()) returns:

Contact_list field name is Id, value is a0C3D0000007x2jUAA
Contact_list field name is Contact__c, value is 0033D00000NopQPQAZ
Contact_list field name is CurrencyIsoCode, value is USD
Contact_list field name is Contact__r, value is Contact: {[email protected], Name=Ronni Adamo, Id=0033D00000NopQPQAZ, CurrencyIsoCode=USD}

I'm struggling with the proper syntax to access contact_list.contact__r [(contact or contact__c)].email. Whenever attempting to access the value in a loop, the code fails to compile with

Error: Compile Error: Variable does not exist: contact__r
  • 1
    Can you post your for loop? Why are you querying into a generic SObject?
    – EricSSH
    Apr 30, 2018 at 18:53
  • If you used the type Junction__c you would have access to the field contact__r, but since its a generic type, you need to use getSObject Apr 30, 2018 at 18:58

1 Answer 1


When using a generic SObject, you need to use getSObject:

for(SObject record: contact_list) {
  Contact conRecord = record.getSObject('Contact__r');
  • Thanks Fox! addresses = (string) contact_IDs.getsobject('contact__r').get('email'); did the trick. Apr 30, 2018 at 20:48

You must log in to answer this question.

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