Retrieving field dynamically from anonymous object

apexcustom-objectdynamic-apexinheritanceobject

I have a scenario where I need to dynamically retrieve fields from a custom object, in which I don't know the type. For the following code, the query is passed in from somewhere else, I just wrote it out for the purposes of this example.

This code works, however, the type is obviously explicit:

House__c o = Database.query('Select Id, NumberOfRooms__c from House__c limit 1');
System.debug(o.get('NumberOfRooms__c'));

So I thought I could write this code:

Object o = Database.query('Select Id, NumberOfRooms__c from House__c limit 1');
System.debug(o.get('NumberOfRooms__c'));

But I get the following error:

Error: Method does not exist or incorrect signature: void get(String)
from the type Object

It looks like the .get() method isn't available on object, but is available on custom objects. Is this inherited from a class higher up in the hierarchy? If so, what can I cast o to to get this method?

Or, alternatively, is there another way to dynamically retrieve the value of fields on the object type?

Best Answer

Change Object to SObject

SObject o = Database.query('Select Id, NumberOfRooms__c from House__c limit 1');
System.debug(o.get('NumberOfRooms__c'));

SObject class has get method to dynamically get field value.

Any standard/custom object extends SObject and SObject extends Object