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.

Get Java™ Phrasebook 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.