简体   繁体   中英

Partially creating immutable object in java

I have an immutable object which also has its builder class. I need a way to create the object in 2 phases where in first phase with a few parameters and in the other with rest. Is there any way or framework to do this?

You could either pass the builder to the second phase, or copy the data from the old object into a new object.

A good builder implementation will have a way of copying an object. For example with lombok, you can use the toBuilder option, which will create a builder from an existing object and allow you to create a new object with the data from the old object.

Here is my suggestion :

Follow Builder design pattern, Have two builders for each phase. I think that would be enough. I doubt there would be a framework for such things.

If you are following all the rules of an immutable object, you cannot do that.
The constructor is called only once per new .

Two possible ways are wrapping or using reflection .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM