Instantiating an Apex class based on dynamic string name with Type class

Somtimes we need to instantiate a Apex class by dynamic value in Salesforce, which can make our program more modular and more readable, such as the below case :

1. Each Contact has its socail fields : “Type__c” and “AccessToken__c”
2. Needs to request its profile via socail api in Apex

First we need to create an interface class, e.g. SocialApi, as the following source :
※A parent class with keyword “virtual” is workable as well.

Then create an Apex class implements SocialApi named “FacebookApi”.

Now we can instantiate “FacebookApi” class and call its method with the value of Contact.Type__c as the following source.

Enjoy it!

Related Post

How to access static resources from Apex, Visualfo... In Apex Normal file (with soql) Normal file (with PageReference.getContent) Zip file (with PageReference.getContent) ※Zip file can not be accessed by soql.
A way to make Thread Sleep in Apex Sometimes we need make apex thread to sleep for a while, sush as testing if the soql with [For Update] works,and as we know the sfdc do not offer a method to sleep the thread. Then I thought it may work if I use the "while", like the following code. ...
Use Salesforce Mini Page Layout in Visualforce Pag... Mini Page Layout is a nice feature of Salesforce,it can be maintained for every parent object in master-detail or lookup relationship in order to display additional record information without jumping to its detail page. Enable Mini Page Layout First,navigate to Customize > User Interface an...
Salesforce CategoryNode sObject in Apex Unit Tests In Salesforce,DML operation is not allowed on CategoryNode sObject,even in Unit Test. Although the 《 Apex Code Developer's Guide》 does not mention it clearly,that CategoryNode object can be accessed in Apex Tests, we have to prepare CategoryNode data first in Setup clicking Cu...