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();
	}

}

Sharing is Caring

Brian is a programmer and technology leader living in Niagara Falls with more than ten years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.