lombok.Getter cheated me

下面這段代碼,IDE里正常顯示。不過,在build時,會報錯。

interface Doable {
    Integer getCode();
}

@lombok.Getter
class DerivedClass implements Doable {
    int code;
}

錯誤信息:

Error:(11, 5) java: DerivedClass不是抽象的, 並且未覆蓋Doable中的抽象方法getCode()
Error:(13, 13) java: DerivedClass中的getCode()無法實現Doable中的getCode()
返回類型int與java.lang.Integer不兼容


下面代碼,IDE直接在int上標紅線,提示錯誤:'getCode()' in 'DerivedClass' clashes with 'getCode()' in 'Doable'; attempting to use incompatible return type

interface Doable {
    Integer getCode();
}
class DerivedClass implements Doable {

    @Override
    public int getCode() {
        return 1;
    }
}

 

關於OOP中的方法覆寫,遵從“一大兩小”原則。其中“兩小”中的一個“小”是派生類的返回值類型應≤父類。就是說,下面代碼是沒有問題的。

interface Doable {
    Number getCode();
}
class DerivedClass implements Doable {

    @Override
    public Integer getCode() {
        return 1;
    }
}

 

 

關於lombok的@Getter註解。首先要知道,我們熟知的lombok,分爲lombok工具和lombok插件(IDEA插件:IntelliJ Lombok plugin)。lombok工具在代碼編譯期爲類生成相應的方法代碼,lombok插件是爲類IDE增強類裏的方法,就是說,lombok爲類生成相關方法簽名(就像我們人肉爲類添加的方法那樣,只不過插件是自動生成的),並告訴IDE。像上面的案例中,IDEA就檢測到DerivedClass類中有getCode方法,所以不會給出錯誤提示。而在編譯期,lombok工具爲DerivedClass生成了int getCode方法,這時,IDEA編譯器發現因不符合java覆寫原則而報錯。

之所以分享這個知識點,則源自昨天的一段代碼。 我在項目中新增了一個枚舉類PlatOrderInTypeEnum,見下面代碼,其中的EnumAbility<T>中有T getCode();方法。自然是想不到會有什麼問題。結果在部署到測試環境時,Jenkins構建時出現如下maven compile error。

/***
 * T_Plat_order表IN_TYPE枚舉--用來標記交易來源 (API/客戶提交/運營提交)
 * @author zhangguozhan
 * 2023-5-15 17:46:02
 */
@Getter
@AllArgsConstructor
@EnumGetByCode
public enum PlatOrderInTypeEnum implements EnumAbility<Integer> {
    API(1, "結算接口提交"),
    MERCHANT(0, "結算後臺提交"),
    BOSS(2, "運營後臺導入");

    private Integer code;
    private String description;

}

Jenkins錯誤截圖

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章