[SalesForce] APEX: Use a dynamic string to create an instance of a class

I have an abstract class called Process that I extend to create a list of processes (List<Process>); each in relation to an object. For now everything works as expected but I'm really hoping to create a very dynamic approach to these processes.

For example I also have a Process__c custom object, and with a SOQL statement I can get a list of all the Process_c records I need for a given context. These records contain the String name of a class that I want to instantiate, but for the life of me I can't seem to find a way to do this.

I've tried something like the following:

String s = 'Account';
List<Process__c> activeProcesses = [SELECT Name FROM Process__c WHERE Active__c = TRUE AND Object__c = :s];
List<String> processNames = Utils.Data.Convert.stringList(activeProcesses, 'Name');

Type t = Type.forName('Process');
List<Process> processes = new List<Process>();
for(String processName : processNames){
    Process p = t.newInstance(processName);
    processes.add(p);
}

The error I'm getting when attempting this is:

Method does not exist or incorrect signature: [Type].newInstance(String)

I really hope the harsh reality isn't that this is just not possible but if it is I need to know that as well, so any insight you have with this question would be greatly appreciated.

Best Answer

Your strategy will work, but your constructor must contain no parameters, and the same goes for your newInstance() call. You pass the name of the Type you want to construct into the Type.forName method.

Type customType = Type.forName('SomeClass');
SomeClass instance = (SomeClass)customType.newInstance();

You probably will want to implement an interface here as well. Something like:

public interface IProcess { void execute(); }
public class Process1
{
    public Process1()
    {
        // instantiation logic
    }
    public void execute()
    {
        // execution logic
    }
}

You would use the above as follows:

IProcess instance = (IProcess)Type.forName('Process1').newInstance();

You don't even really need to cache it for simple cases:

(IProcess)Type.forName('Process1').newInstance().execute();
Related Topic