重載父類別元素 (當類別裡含有自己的類別List的時候)


Posted by Steve Chang on 2022-07-06

其實不確定標題要叫啥,如果有建議的標題麻煩告訴我。

場境

dependency內的物件

Class Category {
    List <Category> children;
}

需要在其上方加上一層,讓他可以多帶自定義的元素返回。

@Data
Class CustomCategory extends Category {
    String customId;
}

實作上看起來就完事了
只要

function CustomCategory toCustomCategory(Category category) {
    CustomCategory customCategory = new CustomCategory();
    if (Objects.nonNull(category.getChildren()) {
        List<CustomCategory> customChildren = new ArrayList<>();
        for (children : category.getChildren()) { 
            customChildren.add(toCustomCategory(children));
        }
        customCategory.setChildren(customChildren);
    }
    customCategory.setCustomId("customId");
    return customCategory;
}

就完事,實作上也可以產出要的回應。
但當另一個專案引用此專案,並以feign client來實作這個client的時候。
因為只有API的介面,當他解析回應的時候就會以

@Data
Class CustomCategory extends Category {
    List <Category> children;
    String customId;
}

來做預設的解析,沒辦法在子節點內也解析為CustomCategory。
也沒辦法

@Data
Class CustomCategory extends Category {
    List<CustomCategory> children;
    String customId;
}

both methods have same erasure, yet neither overrides the other
他們在拆解時是同一個來源的,沒有辦法這樣覆蓋。

解決方式

@Data
Class CustomCategory extends Category {
    Collection<CustomCategory> children;
    String customId;

    public List<Category> getChildren() {
        if (Objects.nonNull(children)) {
            return new ArrayList<>(children);
        } else {
            return null;
        }
    }
}

用Collection去取代原先的List,就可以避免掉無法覆蓋的issue了。
在取出的時候再去複寫getChildren()的內容即可。


#spring-boot #java







Related Posts

程式基礎 —— Javascript 動手做 Part1

程式基礎 —— Javascript 動手做 Part1

網頁常見功能

網頁常見功能

系列文介紹 & 版權聲明

系列文介紹 & 版權聲明


Comments