APEX: Use a dynamic string to create an instance of a class
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();
If you do have a need to pass parameters to the dynamically created class, a way to do that is to create the class by using JSON.deserialize
:
Type t = Type.forName('Process');
Process p = (Process) JSON.deserialize('{}', t);
so that if the class has e.g. fields x
and y
:
public virtual class Process {
Integer x;
String y;
}
you can set values in them like this when the instance is created:
// This could come from e.g. a configuration custom setting
String configClass = 'ProcessSubClass';
String configParameters = '{"x": 34, "y": "Hello world"}';
Process p = (Process) JSON.deserialize(configParameters, Type.forName(configClass));
assuming configClass
is a sub-type of Process
.