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

Getting a Custom Setting in Apex Indirectly

I've been struggling to figure out how to solve this problem.  I have a hierarchical custom setting called "Settings__c."  I'm trying to fetch a field on that setting at the Org level.  The problem lies in the fact that the code does not actually "know" which custom setting or field is being fetched.  The code looks something like this:


public Object fetchCustomHierarchySetting (String setting, String field) {

  Schema.SObjectType objType = this.getObjectType (setting);

  if (objType != null) {



  return null;



The problem is where the "..." is.  I cannot seem to find any method that lets me fetch the org defaults for the hierarchy setting.  Is there some way to accomplish this?  Since the code doesn't know which custom setting is being instantiated, it can't just typecast to the hierarchy setting; and there doesn't seem to be a "parent object' that provides static initializers.


Thanks in advance.


As far as I can tell, you have to know the type of custom setting in advance, because the parent class of a CustomSetting__c is Schema.SObject, the same as a normal custom object. That being said, this is ultimately possible:


map< string, sobject > settings = new map< string, sobject > {
  'Custom_Setting__c' => Custom_Setting__c.getOrgDefaults( ),
  'Other_Setting__c' => Other_Setting__c.getOrgDefaults( )

if( settings.containsKey( setting ) } { return settings.get( setting ).get( field ); }

You'll have to add one entry for each setting type. You might also need to add a special API if you expect customers might be inserting their own custom settings that meet the criteria.