Instantiating Serialized Objects

So far, we’ve used the new operator to create instances of Beans. But there is another way to instantiate Beans that is more flexible and often preferable. The class java.beans.Beans contains a static method named instantiate() that can be used to create an instance of a Bean. This method takes two parameters: a class loader and a string containing the desired Bean’s fully qualified class name. If null is used for the first parameter, instantiate() uses the default class loader. instantiate() first looks for a “pickled” bean, which is nothing more than an object stream file that contains an instance of the serialized state of the Bean class. If it finds such a file, instantiate() creates the new instance directly from that file, without calling the Bean’s constructor. If instantiate() cannot find a serialized file, it uses the new operator to create the new instance in the customary way: by calling the Bean’s default constructor. Therefore, in order for instantiate() to work, the class must provide a constructor that takes no parameters (i.e., a default constructor)—the instantiate() method does not allow you to provide any parameters with which to call the constructor.

To find the pickled bean, instantiate() converts the fully qualified class name into a filename by using the package hierarchy as a file hierarchy, and then adding the .ser file extension. For example, a fully qualified class name of BeansBook.Simulator.Thermostat will be converted ...

Get Developing Java Beans 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.