function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ColoradoMikeColoradoMike 

Suggestion for determining a field's data type when using Dynamic SOQL

Let's say you're using this bit of dynamic Apex:

 

SObject s = [SELECT accountNumber FROM account LIMIT 1];
Object o = s.get('AccountNumber');

 

I'd like to be able to determine the datatype of the generic Object o. ("String" in this case).

 

The assumption here is that the list of fields in the SOQL could vary, so I won't know at design time exactly which fields are being pulled.  It's also possible that the object from which I'm pulling may not always be Account, so I'm hoping to find a dynamic way to know the datatype of the field.

 

I suppose I could do some kind of Describe Fields on the object and then match the name listed with a Map of the DescribeFieldResults, but I'm lazy and would prefer an easier route if possible.

 

Thanks for your suggestions.

 

Mike

SObject s = [SELECT accountNumber FROM account LIMIT 1];
Object o = s.get('AccountNumber');
s.put('AccountNumber', 'abc');

Best Answer chosen by Admin (Salesforce Developers) 
Shashikant SharmaShashikant Sharma

If you don't want to use describe than You have to check for all the data types

 

like this

 

SObject s = [SELECT accountNumber FROM account LIMIT 1];
Object o = s.get('AccountNumber');

if (o instanceof Double)
{
   system.debug(' o is Double');
}
else if (o instanceof Integer)
{
   system.debug(' o is Integer');
}

 That is the only way without describe call.

All Answers

Shashikant SharmaShashikant Sharma

If you don't want to use describe than You have to check for all the data types

 

like this

 

SObject s = [SELECT accountNumber FROM account LIMIT 1];
Object o = s.get('AccountNumber');

if (o instanceof Double)
{
   system.debug(' o is Double');
}
else if (o instanceof Integer)
{
   system.debug(' o is Integer');
}

 That is the only way without describe call.

This was selected as the best answer
ColoradoMikeColoradoMike

Thanks! That was helpful!