Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect
Have you ever faced the problem to find out which Apex classes have implemented the interface and then doing the typecasting to call individual class methods? If your answer is yes, then you will be happy to know that Salesforce’s Spring 23 release can help you now. In today’s post, I will be showing you how to find out which apex classes have implemented an interface. And after finding what we can do with that information. This is the new feature that became GA (Generally Available) in Spring 23 release.
You can read this blog post or watch the video below
Below is the interface
Classes Implementing The Interface
Here is the class that implements the above interface
In the above ccode, there are three concrete classes (Ship, Airplace and Car) that have implemented the interface Vehicle and one abstract class (Train) that has implemented the interface Vehicle.
Here is the code to test
In the above code, I am executing SOQL query to fetch information from ApexTypeImplementor. It is now generally available and has been updated since the beta release. It represents Apex classes that directly or indirectly implement an interface. Using a SOQL query this object gets information about public or global classes and only global classes for installed managed packages.
In the query, I am using IsConcrete. It indicates whether the implementing class is abstract.
Documentation: Click Here
Here is the output:
As you can see, in the debug log, it only printed the concrete class and not the abstract class which is Train. The reason is that in the query, I have mentioned IsConcrete=true.
Let’s Do Typecast
With the information available (which classes have implemented the interface), in the below example, I will do the typecasting and execute method from each of the implementation. Here is the code:
In the above code, I have done the typecasting by converting the indvidual classes into the type of interface and then executing the method.
Vehicle rs = (Vehicle)Type.forName(single.ClassNamespacePrefix, single.ClassName).newInstance();
Here is the output
As you can see from the above image that methods from each of the classes are being called without knowing the actual name of the class. It’s all happening by calling the method using Interface name.
I believe this is a very important and helpful improvement being delivered in Spring 23 release. Developers will be able to write more optimized code using this new feature. Please share your thoughts, ideas in the comment section.
This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.