Surrogate classes are very similar in concept to ObjectSwaps except they're simpler to define.
For example, let's say we want to be able to serialize the following class but it's not serializable for
some reason (for example, there are no properties exposed):
| // Not serializable because it's not a bean because it has no public properties.
| public class MyNonSerializableClass {
| protected String foo;
| }
This could be solved with the following ObjectSwap.
| // A serializable bean with 1 property.
| public class MySerializableSurrogate {
| public String foo;
| }
|
| // An ObjectSwap that swaps out our non-serializable object with our serializable object.
| public class MySwap extends ObjectSwap<MyNonSerializableClass,MySerializableSurrogate> {
| @Override /* ObjectSwap */
| public MySerializableSurrogate swap(MyNonSerializableClass object) {
|
| // Create some serializable class and manually copy the data into it.
| MySerializableSurrogate surrogate = new MySerializableSurrogate();
| surrogate.foo = object.foo;
| return surrogate;
| }
| }
However, the same can be accomplished by using a surrogate class that simply contains a constructor with
the non-serializable class as an argument:
| public class MySerializableSurrogate {
| public String foo;
|
| // Constructor takes in our non-serializable object!
| public MySerializableSurrogate(MyNonSerializableClass object) {
| this.foo = object.foo;
| }
| }
The surrogate class is registered in the same way as a ObjectSwap:
| // Create a JSON serializer that can serialize our unserializable object.
| WriterSerializer serializer = JsonSerializer
| .create()
| .swaps(MySerializableSurrogate.class)
| .build();
When the serializer encounters the non-serializable class, it will serialize an instance of the surrogate
instead.
- {@link oaj.swap.Surrogate}