Dynamic Instance Creation

Sometimes it can be useful to create an object instance without hard-coding its type in a program. For example, your program might include an extensibility mechanism for other developers to add or customize its behavior. One way to do this is to expose an Apex interface, document it, and allow users to provide the name of a custom Apex class that implements the interface. Listing 5.35 is a simplified version of this scenario that can run in the Execute Anonymous window.

Listing 5.35 Creating Instance from Type Name


interface MyType { void doIt(); }
class MyTypeImpl implements MyType {
  public void doIt() { System.debug('hi'), }
}
Type t = MyTypeImpl.class;
if (t != null) {
  MyType mt = (MyType)t.newInstance();
  mt.doIt();
}


Notice that MyTypeImpl is defined as the type to be created in the program on line 5, so it isn’t dynamic. The dynamic form is Type.forName('MyTypeImpl'), which is invalid in the Execute Anonymous window because MyTypeImpl is transient, defined in the scope of the Execute Anonymous code block only. To try the dynamic type lookup, create the interface and class using the Force.com IDE.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.119.206