Implement a nested abstract class using a getter / setter

I have the following abstract class structure:

public abstract class A {
    ...
    private List<B> b;

    public List<B> getB() {
        return b;
    }
    public void setB(List<B> b) {
        this.b = b;
    }
    public static abstract class B {

    }
}

and implement it as follows:

public class AA extends A {
    public static class BB extends B {
        ...
    }

When I now use jackson to display Json on AA, I get an error that it cannot create an instance of A $ B. I think this is because the getter / setter in still refers to B and not to BB, which causes an error. Is there a way I can do this without adding a getter / setter to a subclass?

+4
source share
3 answers

You can add a type capture to make sure b is always correctly typed as follows:

public abstract class A<T extends A.B> {
    ...
    private List<T> b;

    public List<T> getB() {
        return b;
    }
    public void setB(List<T> b) {
        this.b = b;
    }
    public static abstract class B {
        ...
    }
}

and then

public class AA extends A<AA.BB> {
    ...
    public static class BB extends B {
        ...
    }
+2
source

-. , , , , . .

  • Objects.requireNotNull.

Jackson - @JsonCreator @JsonProperty , .

  • .

. , , , , . ? ? ( , public static)

+1

If you create an instance AA, you need an instance of the abstract class B, and you determine nowwhere which instance to use. Just doing some implementation ( BB) is not enough.

0
source

All Articles