I'm using Builder pattern of lombok in my Spring boot project.
@Getters
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
class Parent{
private String _id;
private String name;
}
@Getters
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
class child_1 extends Parent{
private String address;
}
@Getters
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
class child_2 extends Parent{
private String gender;
}
When I get the instance of Parent
if(parent instanceof Child_1){
Child_1 c1=(Child_1) parent;
Parent p=Child_1.builder()._id(c1.get_id()).name(c1.getName()).address(c1.getAddress()).build();
}
else if(parent instanceof Child_2){
Child_2 c2=(Child_2) parent;
Parent p=Child_2.builder()._id(c2.get_id()).name(c2.getName()).gender(c1.getGender()).build();
}
This is perfectly working. But there are some boilerplate codes like _id(c1.get_id()).name(c1.getName())
. I showed here only _id
and name
as an example. But I have more than 20 fields in Parent and more than 10 child classes with many fields. So the parent variables are again and again repeating. Is there any way to cut these boilerplate codes?
I tried something like following when I get Parent
object. Here p
is a Parent object
Parent parent=Parent.builder()._id(p.get_id()).name(p.getName()).build();
if(p instanceof Child_1){
Child_1 c1=(Child_1) parent;
parent=Child_1.builder().address(c1.getAddress()).build();
}
else if(p instanceof Child_2){
Child_2 c2=(Child_2) parent;
parent=Child_2.builder().gender(c1.getGender()).build();
}
But this assigning null
to parent variables since I assign again to parent
object from child classes. Any approaches will be appreciated. thanks in advance
You can use BeanUtils.copyProperties(<Source>, <Target>);
Parent fromChild=null;
if(p instanceof Child_1){
Child_1 c1=(Child_1) parent;
fromChild=Child_1.builder().address(c1.getAddress()).build();
}
Parent parent=Parent.builder()._id(p.get_id()).name(p.getName()).build();
BeanUtils.copyProperties(parent, fromChild);
fromChild
has null values of _id
and name
. So when we create parent
, we can easily overwrite null values
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.