[SalesForce] How to access lookup object field in apex

So, I'm getting the values of the properties of a custom sObject in my org, in an Apex method. So, this is how it works, basically I receive via parameter a list of strings that are the fields that I need to fetch from the sObject. So, the process is this:

for(Item__c item : items){
  for(String field : fields){
     columns.add(String.valueOf(item.get(field)));
  }
}

The fields are being sent from my lightning component, in a way I can directly get them via sObject.get.
The thing is, there is a field that is a lookup field (its called listing_type) and I don't know how can I access a field of the listing_type object. I can't access it directly like this, so how can I achieve this? It should be listing_type__r.name, but if I pass that to the item.get() it doesn't work.

Best Answer

You need to "follow the path", like this:

for(Item__c item: items) {
  for(String field: fields) {
    // Temp variable holds current spot in path
    sObject temp = item;
    // Break into parts; we need to escape . because split uses regex.
    String[] path = field.split('\\.');
    // While we have more path to follow, and current step isn't null...
    while(path.length()>1 && temp != null) {
      // Go to the next step
      temp = temp.getsObject(path.remove(0));
    }
    // Assuming we still have a current spot, we can get the end value here
    if(temp != null) {
      columns.add(String.valueOf(temp.get(path[0])));
    }
  }
}

You could even abstract this into a method if you think you might use it frequently.