Dynamic execution of classes in Apex
Here is a bare-bones example of leveraging the Class Factory design pattern in Apex. It's an interface-based approach that permits dynamic class instantiation. The only requirement is to implement the interface method(s) but the rest of the class internals participating in the class factory can be completely unique (Class1, Class2, etc.)
ClassFactory:
public with sharing class ClassFactory
{
// Class Factory template
public interface IClassFactory
{
void processWork();
}
// Class Factory base class
public virtual class ClassFactoryBase
{
// ... Shared methods go here
}
// Process work
public static void processAllWork()
{
ClassFactoryManager cfm = new ClassFactoryManager();
cfm.newClassInstance('ClassFactory.Class1').processWork();
cfm.newClassInstance('ClassFactory.Class2').processWork();
cfm.newClassInstance('ClassFactory.Class3').processWork();
cfm.newClassInstance('ClassFactory.Class4').processWork();
}
// Class1
public class Class1 extends ClassFactoryBase implements IClassFactory
{
public void processWork()
{
// ... Class-specific work goes here
}
}
// Class2
public class Class2 extends ClassFactoryBase implements IClassFactory
{
public void processWork()
{
// ... Class-specific work goes here
}
}
// Class3
public class Class3 extends ClassFactoryBase implements IClassFactory
{
public void processWork()
{
// ... Class-specific work goes here
}
}
// Class4
public class Class4 extends ClassFactoryBase implements IClassFactory
{
public void processWork()
{
// ... Class-specific work goes here
}
}
}
ClassFactoryManager: (modified - thanks for the suggestion Peter)
public with sharing class ClassFactoryManager
{
public ClassFactoryManager(){}
// Return the appropriate class instance based on className
public ClassFactory.IClassFactory newClassInstance(String className)
{
Type t = Type.forName(className);
return (ClassFactory.IClassFactory) t.newInstance();
}
}
Ahhhh.... much better.