I'd like to solve such problem. I have some abstract class and a concrete class with setters that return the instance of that class:
@MappedSuperclass public abstract class BaseEntity implements Serializable { private Integer id; public Integer getId() { return id; } public BaseEntity setId(Integer id) { this.id = id; return this; } } next abstract:
@MappedSuperclass public abstract class NamedEntity extends BaseEntity { private String name; public String getName() { return name; } public NamedEntity setName(String name) { this.name = name; return this; } } and finally a concrete class:
@Entity public class Person extends NamedEntity { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } I'd like to use this kind of builder but in current setup it's not working due to different return types of parent setters
public Person build() { Person person = new Person() .setId(1); //return BaseEntity instead of Person .setName("name") //returns NamedEntity instead of Person .setAddress("foo"); //return Person! return person; } of course ther's a workaround with overriden setters but.... can it be done other way using generics?
@Override public Person setId(Integer id) { super.setId(id); return this; } @Override public Person setName(String name) { super.setName(name); return this; }
BaseEntity? Builders don't have to be fluent. It looks like you're just constructing aPersonthen setting its attributes. What's wrong withperson.setId(1);,person.setName("name");, etc.?