Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

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

Asked by Behailu Jul 19, 2021 4.7K views 2 answers
Share

About this question

I have an abstract class called Process that I extend to create a list of processes (List); 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 activeProcesses = [SELECT Name FROM Process__c WHERE Active__c = TRUE AND Object__c = :s]; List processNames = Utils.Data.Convert.stringList(activeProcesses, 'Name'); Type t = Type.forName('Process'); List processes = new List(); 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.

Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on May 30, 2024

In Salesforce Apex, creating an instance of a class dynamically using a string involves leveraging the Type class. This approach is useful when the class name is determined at runtime. Here’s how you can achieve this:

Steps to Dynamically Create an Instance of a Class in Apex

Class Names in String Form:

You start with the class name in string form.

  String className = 'MyClass';

Using the Type Class:

Use the Type.forName method to get the Type reference for the class.

Type t = Type.forName(className);

Instantiate the Class:

Create an instance of the class using the newInstance method of the Type class.

Object obj = t.newInstance();

Casting to the Appropriate Type:


Cast the object to the specific class type if you need to call methods on it.

MyClass instance = (MyClass) obj;
instance.myMethod();

Complete Example

Here’s a complete example demonstrating these steps:

public class DynamicInstanceCreator {
    public void createInstance() {
        // The class name is provided as a string
        String className = 'MyClass';
        // Get the Type reference
        Type t = Type.forName(className);
        // Create an instance of the class
        Object obj = t.newInstance();
        // Cast the object to the appropriate class
        MyClass instance = (MyClass) obj;
        // Call a method on the instance
        instance.myMethod();
    }
}
public class MyClass {
    public void myMethod() {
        System.debug('Method executed!');
    }
}

Handling Exceptions

Check Existence of the Class:

Handle cases where the class might not exist.

try {
    Type t = Type.forName(className);
    Object obj = t.newInstance();
} catch (TypeException e) {
    System.debug('Class not found: ' + e.getMessage());
}
Was this helpful?

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.