Skip to content

Custom instance creator

Engin1980 edited this page Jan 29, 2018 · 2 revisions

Custom instance creators are required when there is a need of creation of new instance of a class which does not have a public parameter-less constructor.

Why

During deserialization, when objects are read from the XML file, there is a need to create instances of classes to be filled as field values. However, very often some classes do not have a public constructor without parameters, or, at specific cases, a programmer needs to do more stuff than the instance creation using constructor. Using instance creator a programmer is able do define how a new instance of a class is created.

So, you need a instance creator when:

  • a deserialization process needs to create an instance of a class which does not have accessible parameter-less constructor. In worst case, you will get an exception during deserialization due to this issue,
  • you need to do some more operations after the simple constructor call, like some more complex initialization of the object.

How

Creation of own instance creator class

To create own instance creator, you have to create a class and implement the interface IInstanceCreator<T>. You need to specify:

  • type parameter T defining what type is instantialized using your instance creator, like public class MyTypeCreator implements IInstanceCreator<MyType>
  • implement the method getTypeName() to return the name of the type instantialized using your instance creator, typically using very simple way like return MyType.class.getName(),
  • implement the method createInstance with the code creating the new instance of the instantialized class.

Making instance creator active

The de/serialization process needs to know which instance creator it should use. To specify that the instance creator should be used, its instance must be added into settings' property collection instanceCreators, e.g. settings.getInstanceCreators().add(new MyTypeCreator()).

Predefined creators

Some creators has already been defined in eng.eSystem.xmlSerialization.common.instanceCreators package.

Example

AWT Color instance creator

java.awt.Color class cannot be instantialized using parameter-less constructor. An example of color creator can be found in repository.

AWT Color instance creator usage

You need to create settings, register instance creator in the settings and create the serializer using the settings.

Settings settings = new Settings();
settings.getInstanceCreators().add(new AwtColorCreator());
XmlSerializer serializer = new XmlSerializer(settings);
Object o = serializer.deserialize(xmlFileName, Type.class);

Project

Simple introduction

Common concepts

Clone this wiki locally