[SalesForce] Using Type class to call static methods

The Type class provides a way to dynamically instantiate a class based on a String name, so we can access member variables and instance methods. Is there a way to access static methods using this same mechanism?

What I'd like to do:

global interface Vehicle {
  Long getMaxSpeed();
  String getType();
  // added to sample, not possible
  static String getSomething();
}

global class VehicleImpl implements Vehicle {
  global Long getMaxSpeed() { return 100; }   
  global String getType() { return 'Sedan'; }
  // added to sample
  global static String getSomething() { return 'Something'; }
}

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());       
        // added
        System.debug('Something?: ' + t.getSomething());       
    }
}

Best Answer

Nope, at time of writing, the Type class can't do that.

The Type class can instantiate a class based on a string...and that's about it. Yes, there are a few other methods, but I've never come across a situation where I've actually used anything other than Type.forName() and Type.newInstance().

About the closest you'd be able to get is to have a public, non-static method in your target class (or any class, really) that calls your class's static method. I've personally used something close to this in the trigger framework I developed for my company (I retrieve a static class variable, rather than call a static method).

I can't quite put my finger on it, but having a public method that calls a class's static method feels like it defeats the purpose of having a static method.

Related Topic