How would we return instance of classes based on class name using reflection with apex

Situation

Imagine a scenario where you need to get an instance of a class based on the class name. The original way of doing this in apex is a bunch of if else statements where you need to read the class name and return an instance of an object based on class name. How can we create one condition where we can return an instance of a class based on input class name?

Solution

1. Create an interface and have all the classes implement the interface.

2. Create a factory method where you would read the class name and return the instance of the class based on the class name using reflection.

3. Look at the below method where it reads the class name. It checks if the class exists in the org and then using the forname returns an instance. You might want to do a null check to make sure your code works.

 

public AB_Processor_INF getProcessor(String processorType)
{
String className = ‘Proc_’+processorType;
if([SELECT id from apexclass WHERE Name = :className].size() != 1)
{
throw(new PkException(‘Unknown Processor for AB : processorType passed ‘+ processorType));
}
return (AB_Processor_INF)Type.forName(className).newInstance();
}

Please feel free to enter your comments and let me know if there are any questions..

Buyan

Please Subscribe

Subscribe to our mailing list to get tips on maximizing your salesforce

We respect your privacy.

Please subscribe

Subscribe to our mailing list and get tips to maximize salesforce to your email inbox.

I am honored to have your subscription. Stay tuned for tips to maximize your salesforce investment

Something went wrong.

buyan47

Author: buyan47

Hi there! My name is Buyan Thyagarajan. I am a Salesforce consultant specializing in Higher Education, Manufacturing and Marketing Automation. My blogs will help you to maximize your Salesforce CRM investments, prevent problems beforehand and make the right decisions. If you need to talk to me right away, you can email me at buyan47@gmail.com or call me at 302-438-4097

Leave a Reply

Your email address will not be published. Required fields are marked *