O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required