Search code examples
javalombok

A way to replace the object type for a field in a POJO that extends another POJO


Lets say I have class

public class ParentClass {
    private String field1;
    private String field2;
    private String field3;
    private List<AnotherParentPojo> evses;
}

public class AnotherChildPojo extends AnotherParentPojo {
    private String fieldA;
    private String fieldB;
    private String fieldC;
}

public class ChildClass extends ParentClass {
    private List<AnotherChildPojo> evses;
}

However this leads to the error "both methods have same erasure, yet neither overrides the other" in the ChildClass. I am aware its not possible to override a field but is there any way to achieve this without having to change ParentClass or AnotherParentPojo? I only have control over the ChildClass and AnotherChildPojo


Solution

  • As you mentioned @Data annotation I assume, you are using lombok [1].

    The issue issue that ParentClass and its child ChildClass basically declare same setters/getters but with different type erasure.

    Even though you cannot see them, they are there (lombok magic).

    In order to understand what is happening, I advise you to de-lombok the actual code.

    public class ParentClass {
    
    ...
    
        public List<AnotherParentPojo> getEvses() {
            return evses;
        }
    
        public void setEvses(List<AnotherParentPojo> evses) {
            this.evses = evses;
        }
    
    ...
    
    }
    
    public class ChildClass extends ParentClass {
    ...
    
        public List<AnotherChildPojo> getEvses() {
            return evses;
        }
    
        public void setEvses(List<AnotherChildPojo> evses) {
            this.evses = evses;
        }
    ...
    }
    

    Solution

    Solution might be to just rename one of the "clashing" fields or turn off generation of setter and getter using @Setter(AccessLevel.NONE) @Getter(AccessLevel.NONE) annotations for particular field.


    [1] https://projectlombok.org/