How do I determine at run time the classes that implement an interface using the tooling API?
1 Answer
Edit:
We can now query the ApexTypeImplementator table to find all public and global classes that implement a given interface locally, as well as global classes in managed packages that implement a specified interface.
Original Answer:
For the most usual cases, I use an SOSL to find them:
ApexClass[] classes = (ApexClass[])[FIND 'database.batchable'
IN ALL FIELDS
RETURNING ApexClass(Id, Name)][0];
You can also do this dynamically based on a variable:
ApexClass[] classes = (ApexClass[])[FIND :interfaceName
IN ALL FIELDS
RETURNING ApexClass(Id, Name)][0];
Keep in mind that this also "searches" comments, so you may need to do some post-retrieval parsing using a Pattern if this is a concern, or if the class as a default constructor, you can also:
Boolean classImplementsInterface = Type.forName(classes[0].Name).newInstance()
instanceOf Database.Batchable<SObject>;
-
This seems to fail in a customer org. Is it possible, that SOSL does not have access to the packed classes, even if the sosl is called within the package itself? If so, is there any new solution for this problem? Commented Aug 26, 2019 at 11:05
-
@Basti, When I perform a search in the developer console I can confirm the search does not return any results for packaged code...– StijnCommented Aug 26, 2019 at 11:32
-
@Stijn sure, but these calls happen from outside the package, so the body of the classes should better be hidden. Commented Aug 26, 2019 at 13:20
-
1@Basti, it is possible using the Tooling API to retrieve ApexClass information. It also displays which interfaces are implemented, even in packaged ApexClass. But I am not really familiar with the Tooling API and not sure if there is an effective way of retrieving all classes implementing X. Use the rest explorer and use the following URL to inspect an ApexClass: /services/data/v45.0/tooling/sobjects/ApexClass/APEX_CLASS_ID– StijnCommented Aug 30, 2019 at 11:54
-
1@sfdcfox this came up when I was searching for a solution to do this, and I just wanted to mention that a better solution is now available. You can now query the ApexTypeImplementor object using SOQL to see what classes implement a particular interface. You may want to adjust your answer to include this. I'm not positive if this is still in beta or GA (I can't find anything on whether it was released GA). developer.salesforce.com/docs/atlas.en-us.sfFieldRef.meta/… Commented Dec 21, 2022 at 16:34