Dynamic Apex & Metadata Access
What Is Dynamic Apex?
Short Description
Dynamic Apex lets your code adapt at runtime based on object names, field names, or metadata—without hardcoding them.
Simple Explanation
Dynamic Apex is like a universal remote—one controller that works for many devices.
Gist (Quick Revision)
Dynamic Apex makes code flexible and reusable by reading metadata at runtime.
1. Schema Describe (Metadata Access)
What Is Schema Describe?
Schema Describe allows Apex to read Salesforce metadata such as:
-
Objects
-
Fields
-
Data types
-
Permissions (CRUD/FLS)
Real-Life Example
A form that shows fields based on configuration, not hardcoded rules.
Basic Schema Describe Example
Schema.DescribeSObjectResult d =
Account.SObjectType.getDescribe();
System.debug(d.getName());
System.debug(d.isCreateable());
Describe Fields Dynamically
Map<String, Schema.SObjectField> fields =
Account.SObjectType.getDescribe().fields.getMap();
for (String fieldName : fields.keySet()) {
System.debug(fieldName);
}
Why Schema Describe Matters
-
Build generic utilities
-
Enforce security dynamically
-
Reduce code duplication
Gist (Quick Revision)
Schema Describe lets Apex understand Salesforce structure at runtime.
2. Type Class & Reflection
What Is the Type Class?
The Type class enables reflection—creating and working with classes dynamically by name.
Simple Explanation
Reflection lets Apex discover and create objects at runtime.
Real-Life Example
A plugin system where logic is chosen based on configuration.
Type Class Example
Type t = Type.forName('MyService');
Object obj = t.newInstance();
Calling Methods Dynamically (Conceptual)
((MyService)obj).execute();
When to Use Reflection
-
Frameworks
-
Plugin-style architectures
-
Highly configurable systems
Gist (Quick Revision)
The Type class allows dynamic class loading and execution.
3. Dynamic Apex Use Cases
Use Case 1: Generic Trigger or Service
One handler works for many objects using metadata.
Use Case 2: Security Enforcement
Check CRUD/FLS dynamically:
if (Schema.sObjectType.Account.isUpdateable()) {
update acc;
}
Use Case 3: Config-Driven Logic
Control behavior using:
-
Custom Metadata
-
Custom Settings
Change behavior without changing code.
Use Case 4: Generic Data Processing
Process records based on object name:
String objName = 'Account'; SObject sobj = Schema.getGlobalDescribe().get(objName).newSObject();
Risks & Best Practices
⚠️ Overuse can:
-
Reduce readability
-
Make debugging harder
✅ Best practice:
-
Use Dynamic Apex only when needed
-
Keep logic documented and tested
Gist (Quick Revision)
Dynamic Apex is powerful—use it for flexibility, not everywhere.
