I have a super class:
@Getter
@SuperBuilder(toBuilder = true)
public class Animal {
private Integer size;
}
and several subclasses for it
@Getter
@SuperBuilder(toBuilder = true)
public class Dog extends Animal{
private String color;
}
As you can see, both of the above classes are immutable. Also I have a generic class which computes on any subclass of animal. I am creating a new instance of the animal here with increased size.
public class GrowAnimal<T extends Animal> {
public T execute(T animal) {
// Here I need to explicitly cast to T
T newAnimal = (T) animal.toBuilder()
.size(animal.getSize() + 1)
.build();
return newAnimal;
}
}
There are several problems with this approach:
- I cannot make Animal an abstract class
- It can get pretty unsafe if i have more transformation classes like GrowAnimal
- If someone adds a new subclass of animal and forgets to add SuperBuilder to it, The GrowAnimal will just copy the super-class attributes.
Is there a better way to clone T? I would want to retain all the other attributes of the animal (for example, color of the dog) unchanged in the new instance created. Instead of cloning, I could use setters to mutate the incoming object but that is a code smell.