Friday, June 1, 2012

Dynamic Apex


Dynamic Apex:
   This is enable developer to create more flexible apps.
  • Access sObject and fields:
      Apex Describe the information provides sObjects and fields access by using methods.
 Token—a lightweight, serializable reference to an sObject or a field that is validated at compile time.
 Describe result—an object that contains all the describe properties for the sObject or field. Describe result objects are not serializable, and are validated at runtime.

Methods of Describe Call:
// Create a new account as generic type sObject
sObject s = new Account();
// Verify that the generic sObject is the Account sObject
System.assert(s.getsObjectType() == Account.sObjectType);
// Get the sObject describe result for Account object
Schema.DescribeSObjectResult r = Account.sObjectType.getDescribe();
// Get the field describe result for Name field on the Account object
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is token for the Name field on an Account object
System.assert(f.getSObjectField() == Account.Name);
// Get the field describe result from the token
f = f.getSObjectField().getDescribe();
// Use the Schema getGlobalDescribe method to return a map
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

  • Dynamic SOQL/SOSL/DML:

1.Dynamic SOQL refers to the creation of a SOQL string at runtime with an Apex script. Dynamic SOQL enables you to create more flexible applications.
Dynamic SOQL:  List<sObject> L = Database.query(string);

      2.Dynamic SOSL refers to the creation of a SOSL string at runtime with an Apex script. Dynamic SOSL enables you to create more flexible applications.
Dynamic SOSL:   List<List <sObject>> myQuery = search.query(SOSL_search_string);

          3.To create a new sObject of a given type, use the newSObject method on an sObject token. Note that the token must be cast into a concrete sObject type (such as Account).
Dynamic DML:    Object o = s.get('AccountNumber'); s.put('AccountNumber', 'abc');

            4. To access sObject and fields we can used describe call.
Describe Call:    Schema.DescribeSObjectResult r = Account.sObjectType.getDescribe();

No comments:

Post a Comment