Salesforce Developer Apex Dynamic


// Salesforce - Developer - Dynamic Apex:

We can, at runtime, introspect sObjects and use this information to react 
dynamically to the particular object.  We can also write dynamic SOQL and SOSL 
queries, where the queries are dynamically constructed at runtime.

sObjects contain metadata, such as their name, field names and types, default 
fields values and so on.  We can write applications that introspect this 
information and change behavior based on what is discovered.

There are two types of introspection:

1. compile-time introspection
2. run-time introspection

In compile time introspection, we can create tokens that represent information 
about the metadata of an sObject.  These tokens are serializable and lightweight 
and are ideal for many programming needs.

Here is an example that determines whether an sObject or list of sObjects is 
of a particular data type:

SObject s = [select id from account limit 1];
System.assertEquals(s.getSObjectType(), Account.sObjectType);

List<sObject> lst = new Account[]{};
// Verify if the list of sObjects contains Account tokens
System.assertEquals(lst.getSObjectType(), Account.sObjectType);

Similarly, we can retrieve a token for a field of an sObject:

Schema.SObjectField f = Account.AccountNumber;

We can also use runtime calls to set of getDescribe() methods to introspect 
sObjects.  For example, if we had an Account object that has an Industry field 
that is a picklist, we can determine the possible values of a picklist, and 
all child relationships of the sObject:

Schema.DescribeFieldResult f = Account.Industry.getDescribe();
List<Schema.PicklistEntry> p = f.getPicklistValues();
List<Schema.ChildRelationship> c = f.getChildRelationships();

The return information is quite comprehensive.  For example, for a field, we can 
determine everything from whether the field is an ID or a name field, to whether 
it is nillable, unique, case sensitive, or its precision if it is of type 

Dynamic queries:

sObject c = Database.query('select from Contact limit 1');
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License