function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sfdc Beginnersfdc Beginner 

Type Class

What is the Use of Type Class in Salesforce and Where do we Use it in Realtime?
Best Answer chosen by sfdc Beginner
salesforce mesalesforce me

         Use the forName methods to retrieve the type of an Apex class, which can be a built-in or a user-defined class. Also, use the newInstance method if you want to instantiate a Type that implements an interface and call its methods while letting someone else, such as a subscriber of your package,provide the methods’ implementations.

Example: Instantiating a Type Based on Its Name:---

The following sample shows how to use the Type methods to instantiate a Type based on its name. A typical application of this scenario is when a package subscriber provides a custom implementation of an interface that is part of an installed package. The package can get the name of the class that implements the interface through a custom setting in the subscriber’s org. The package can then instantiate the type that corresponds to this class name and invoke the methods that the subscriber implemented.

In this sample, Vehicle represents the interface that the VehicleImpl class implements. The last class contains the code sample that invokes the methods implemented in VehicleImpl.

This is the Vehicle interface:-
global interface Vehicle {
    Long getMaxSpeed();
    String getType();

This is the implementation of the Vehicle interface:--

global class VehicleImpl implements Vehicle {
    global Long getMaxSpeed() { return 100; }    
    global String getType() { return 'Sedan'; }

The method in this class gets the name of the class that implements the Vehicle interface through a custom setting value. It then instantiates this class by getting the corresponding type and calling thenewInstance method. Next, it invokes the methods implemented in VehicleImpl. This sample requires that you create a public list custom setting named CustomImplementation with a text field namedclassName. Create one record for this custom setting with a data set name of Vehicle and a class name value of VehicleImpl.
public class CustomerImplInvocationClass {

    public static void invokeCustomImpl() {
        // Get the class name from a custom setting.
        // This class implements the Vehicle interface.
        CustomImplementation__c cs = CustomImplementation__c.getInstance('Vehicle');
        // Get the Type corresponding to the class name
        Type t = Type.forName(cs.className__c);
        // Instantiate the type.
        // The type of the instantiated object 
        //   is the interface.
        Vehicle v = (Vehicle)t.newInstance();
        // Call the methods that have a custom implementation
        System.debug('Max speed: ' + v.getMaxSpeed());
        System.debug('Vehicle type: ' + v.getType());