O'Reilly logo

Developing Java Beans by Robert Englander

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

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 ...

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