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(); ...

Get Development with the Force.com Platform: Building Business Applications in the Cloud, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.