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

Time:12-17

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

CodePudding user response:

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/

CodePudding user response:

If Lombok's @Data annotation is applied to both ParentClass and ChildClass, appropriate getters/setters are generated:

// ParentClass
public void setEvses(List<AnotherParentPojo> list) {...}
public List<AnotherParentPojo> getEvses() {...}

and the name clash occurs in ChildClass as it is inherited from ParentClass

// ChildClass
public void setEvses(List<AnotherChildPojo> list) {...}
public List<AnotherChildPojo> getEvses() {...}

If access to ChildClass is available, the simplest solution would be just to rename its evses field, thus renaming the getters/setters and resolving the name conflict.

  • Related