Category Image Instantiating inner classes using Class.forName


I designed a class with a number of pluggable behaviours using the strategy pattern . However this time, I decided to implement the concrete Strategy algorithm classes as inner classes of the Context class just to keep the code organized and reduce the number of tiny classes hanging around the project. Rather than use a bunch of if statements, the concrete Strategy class was simply created using its text name which came from an attribute of the Context class.

...It turns out that there is an implicit constructor for inner classes that passes the outer enclosing class as a reference .....

This problem drive me nuts for an hour this morning. I designed a class with a number of pluggable behaviours using the strategy pattern . However this time, I decided to implement the concrete Strategy algorithm classes as inner classes of the Context class just to keep the code organized and reduce the number of tiny classes hanging around the project. Rather than use a bunch of if statements, the concrete Strategy class was simply created using its text name which came from an attribute of the Context class. What drove me nuts was I kept getting a java.lang.InstantiationException.

It turns out that there is an implicit constructor for inner classes that passes the outer enclosing class as a reference ..... I didn't know!!

I finally found the details of how to use Class.forName to instantiate inner classes in this thread:
http://forum.java.sun.com/thread.jspa?forumID=31&messageID=2617957&threadID=540272

Posted: Monday - March 20, 2006 at 11:59 AM        


Published by