0

Is there a way to mimic dynamic casting in apex. From my understanding, dynamic casting is not available in Apex.

Are there any design patterns that can mimic 'Dynamic Casting'?

A user below listed that the following is acceptable.

String listType = 'Account';
List<SObject> sobjList = (List<SObject>)Type.forName('List<' + listType + '>').newInstance();

Can we do this:

String type = 'Date';
SObject sObjFieldType = (SObject)Type.forName(type).newInstance();

1 Answer 1

6

The closest thing we have available to us at this time is the Type class

Type.newInstance() returns an Object, which still must be cast statically, but it still is enough to enable the type shenanigans required for, say, a factory method.

ex.

String listType = 'Account';
List<SObject> sobjList = (List<SObject>)Type.forName('List<' + listType + '>').newInstance();

or

Superclass subInstance = (Superclass)Type.forName('Subclass').newInstance();
subInstance.inheritedMethod();
subInstance.interfaceMethod();
4
  • I cannot find any documentation regarding .inheritedMethod() and .interfaceMethod(). Jun 4, 2019 at 13:05
  • @MatthewMetros those were just examples, not actual methods. The idea is that if Superclass has a method x(), and Subclass extends Superclass, you are able to call subInstance.x(). Similar thing for if Superclass is an interface, and Subclass implements that interface.
    – Derek F
    Jun 4, 2019 at 13:07
  • Is the following possible? String type = 'Date'; SObject sObjFieldType = (SObject)Type.forName(type).newInstance(); Jun 4, 2019 at 13:10
  • Date is a primitive type, not an SObject, so no. This approach is really only useful for things that extend a class, implement an interface, are SObjects, or things like Lists or the "value" type of a Map (Sets and the "key" type of a Map can't really handle any type casting. Explaining why requires some decent knowledge of Type Theory and the Apex/Java type system, which is way beyond the scope here).
    – Derek F
    Jun 4, 2019 at 13:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .