Loading and Instantiating a Class Dynamically


Class personClass = Class.forName(personClassName); Object personObject = personClass.newInstance(); Person person = (Person)personObject;



Using the Class.forName() and the newInstance() methods of a Class object, you can dynamically load and instantiate a class when you don't know the class's name until runtime. In this phrase, we load the class using the Class.forName() method, passing the name of the class we want to load. This returns a Class object. We then call the newInstance() method on the Class object to instantiate an instance of the class. The newInstance() method returns a generic Object type, so in the last line, we cast the returned object to be the type we are expecting to have.

This phrase is particularly useful in the scenario in which you have one class that extends a base class or implements an interface, and you might want to store the name of the extension or implementation class in a configuration file. This would allow the end user to dynamically plug in different implementations without having to recompile the application. For example, if we had the code from the phrase in our application, and the following code in a plug-in to the application, we could have the application dynamically instantiate a BusinessPerson object at runtime by specifying the full class name of the BusinessPerson object in a configuration file. Before executing our phrase, we would read the class name from the configuration file and set the personClassName variable to that value.

public class BusinessPerson extends Person {  //class body, extends the behaviour of Person class }


The application code in this case would have no hard-coded references to the actual BusinessPerson class. As a result, in your application you only have to hard-code the more generic base class or interface, and you can dynamically configure a specific implementation at run-time by editing a configuration file.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net