Find your content:

Search form

You are here

Determine if a Type implements an interface

 
Share

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.


Attribution to: Daniel Ballinger

Possible Suggestion/Solution #1

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);

Attribution to: Daniel Ballinger

Possible Suggestion/Solution #2

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.


Attribution to: techtrekker
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/3985

My Block Status

My Block Content