-
Notifications
You must be signed in to change notification settings - Fork 0
Custom instance creator
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.
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.
To create own instance creator, you have to create a class and implement the interface IInstanceCreator<T>. You need to specify:
- type parameter
Tdefining what type is instantialized using your instance creator, likepublic 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 likereturn MyType.class.getName(), - implement the method
createInstancewith the code creating the new instance of the instantialized class.
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()).
Some creators has already been defined in eng.eSystem.xmlSerialization.common.instanceCreators package.
java.awt.Color class cannot be instantialized using parameter-less constructor. An example of color creator can be found in repository.
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);