function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ErikOSnet0ErikOSnet0 

Reflection?

Does Apex support reflection

 

I have a class that does a lot of parsing and, based on the results, invokes different classes that support an interface.  Of course, in order to instantiate the class, it has to create a compile time dependency on the class, which also can create a dependency on custom objects and fields.  

 

Now that I want to reuse and extend this for another project that will be deployed to a different SFDC instance, all these dependencies become an issue, because those custom fields and objects are not in the other SFDC instance.  

 

On top of this, I want it to all become completely configurable with the parsing and invoking to be part of a re-usable framework.  I want to declare which classes to instantiate based on the data being parsed to be configurable (runtime configurable object factory).  

 

This is a common use case for reflection.  Can I do this in SFDC?  Or, are we doomed to not be able to use reusable configurable code?

 

gm_sfdc_powerdegm_sfdc_powerde

To answer your first question, Apex does not support reflection.  So you cannot instantiate a class from its name read as a string.  However there may be other ways to achieve your goal.  

 

It is possible to avoid dependence on specific custom objects and custom fields by using dynamic SOQL and dynamic DML.  (You can read more about these topics here - http://www.salesforce.com/us/developer/docs/apexcode/index_CSH.htm#apex_dynamic.htm).  You could thus use a single generic implementation of your interface to meet your needs.  If you still need multiple implementations, you can do a name to Apex class mapping but again, there is no reflection and so this needs to be a compile-time configuration. 

 

ErikOSnet0ErikOSnet0

I don't think this is possible.  The custom fields come into play when it goes to create Account and Contact records using an Insert.  To my knowledge, you can't bulk insert using dynamic SOQL.  Please correct me if I'm wrong. 

 

The custom fields aren't needed by the app, per se.  The user that created them made them mandatory without a default value, so they have to be populated in order to do the Insert.  

 

sfdcfoxsfdcfox

Update!

 

Salesforce.com's Summer '12 Edition will include some reflection capabilities. You can now dynamically instantiate classes that are not known at compile-time based on interfaces. You can't apparently iterate through all classes and determine their interfaces, but you can at least create instances on the fly if you somehow know the class instance (e.g. a custom setting value).