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

Leave a Reply

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

Get free tips on Salesforce
Get free tips on Salesforce
We respect your privacy.