serializer icon indicating copy to clipboard operation
serializer copied to clipboard

Question: are immutable objects with builders supported?

Open remal opened this issue 1 year ago • 3 comments

In our code, we have a lot of DTOs like this:

@lombok.Value
@lombok.Builder
class Entity {

  String requiredField;

  @lombok.Builder.Default
  String requiredFieldWithDefaultValue = "default value";

}

For the provided example, Lombok generates a private constructor, getters, and a builder with a default value for requiredFieldWithDefaultValue field.

Will such an object be correctly deserialized by this library? By "correctly" I mean:

  1. Deserialization works with a private constructor.
  2. If the requiredFieldWithDefaultValue field was added only in the second version of the class, deserializing content from the first version (without this field) will have "default value" as a default value for the field.

remal avatar Feb 26 '24 00:02 remal

  1. Deserialization works with a private constructor.

Yes, that will work.

  1. If the requiredFieldWithDefaultValue field was added only in the second version of the class, deserializing content from >the first version (without this field) will have "default value" as a default value for the field.

No, the default value will be ignored, as the original serialized version did not have the field it will be set to ‘null’

The Serializer will not call constructors or other methods of the (de)serialized classes if no specialized handler is implemented.

hg-ms avatar Feb 26 '24 09:02 hg-ms

@hg-ms, thanks for the answer!

Could you please elaborate a bit on how it works? Does this library generate bytecode? Does it use a private all-args constructor? Any other way? You can just share a link to the class(es) that does it.

Thanks!

remal avatar Mar 06 '24 20:03 remal

By default we use sun.misc.Unsafe.allocateInstance(Class<?>) to create object instance and later on the fields and primitive values are populated using the “put” methods of sun.misc.Unsafe. This is implemented in org.eclipse.serializer.memory.sun.JdkMemoryAccessor. There is also an alternative MemoryAccessor “MemoryAccessorGeneric” that uses reflections instead of Unsafe.

The object creation is done by our TypeHandlers that are generated dynamically if there is no specialized handler for a class provided, they also define how objects are (de)serialized. You may have a look into BinaryHandlerGenericType.java if you are interested in details.

hg-ms avatar Mar 07 '24 08:03 hg-ms

There has been no further communication since March, and no actions have been taken on our end. If you encounter another problem, please feel free to create a new issue or reopen this one.

zdenek-jonas avatar Jul 12 '24 12:07 zdenek-jonas