9

I've created an interface within a managed package that installers can implement (much like the example here and Making your managed package extensible with Apex Plugins). Clients can then configure their class name in a custom setting and I invoke it as required.

Given just the class name as a string, how can I determine if the class it represents implements my interface?

Do I need to construct an instance from the Type so I can use instanceOf?

string className = 'someCustomClientClass';
Type t = Type.forName(className);
object testInstance = t.newInstance();
System.assert(testInstance instanceOf SomeClass.SomeInterface);

I guess this will work (with some additional checks that the type actually exists), but I'd prefer to just rely on the Type object rather than creating an instance and invoking whatever their constructor does.

8

Unlike Java, where the “Class“ can be constructed and checked for inheritance, the Type in Apex is fairly limited. One of the few operations it permits is instantiation as an Object of the Type.

The instanceof operator applies only to Object Instances, which would imply that the Type will have to be instantiated to check for inheritance.

(An alternative to instanceof might be attempting to cast it to the interface and handling the 'CastException')

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_type.htm

Whilst I understand your intention to avoid loading any expensive construction logic, I'm guessing you will have to construct the classes for purposes of the actual callback.

  • 1
    I suspect you are right and my only option is to create an object and then use instanceOf or a cast. I'll leave this open for a bit to see if there are any other ideas before accepting. Thanks. – Daniel Ballinger Nov 1 '12 at 22:43
2

The Winter '20 release will include the new System.Type.isAssignableFrom(sourceType) method.

This avoids the need to create an actual instance of a class type to determine if it is assignable to another type.

E.g.

string className = 'someCustomClientClass';
Type t = Type.forName(className);

System.assert(SomeClass.SomeInterface.class.isAssignableFrom(t);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.