Apex How to Get a List of Fields Set on an sObject

Sharing is Caring

I recently had a requirement to dynamically determine what fields had been set or queried on a sObject, so that a comparison could be done on what was actually stored in Salesforce’s Datastore.

Surprisingly, there’s no way method on the sObject that let’s you tell what’s actually been queried or set. So without further ado, here’s the method that I decided to use because it’s much faster than doing a describe and catching every exception.

public class Utils {
	//Takes in an sObject and determines what values have been queried or set on the page.
	public static Set<String> getFieldsSet(sObject obj)
	{
		if (obj == null)
			return new Set<String>();
			
		Map<String, Object> fieldValues = (Map<String, Object>) JSON.deserializeUntyped(JSON.serialize(obj));
		
		if (fieldValues.containsKey('attributes'))
			fieldValues.remove('attributes');
		
		return fieldValues.keySet();
	}

}

Author: Brian Cline

Brian is a programmer living in Niagara Falls with ten years of development experience. He is passionate about automation, business process re-engineering, and gamification. For the last six years or so, he has been working with Salesforce and JavaScript.

Related Posts

Sharing is Caring