代碼筆記

「Java筆記」 用 Lombok 解決代碼 Getter/Setter等 又長又臭的問題

Java的一大特點,就是啰嗦。尤其是每個類中都要寫Getter和Setter,真的是又長又丑。所以今天這裡推薦一個神器:Lombok

那該怎麼消除這些冗餘的代碼?簡單幾步操作。

首先看下原始代碼:

@Entity
@DynamicUpdate//動態更新
public class ProductCategory {
    /**
     * 類目id
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer categoryId;

    /**
     * 類目名字
     */
    private String categoryName;

    /**
     * 類目編號
     */
    private Integer categoryType;

    private  Date createTime;

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    private Date updateTime;

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public Integer getCategoryType() {
        return categoryType;
    }

    public void setCategoryType(Integer categoryType) {
        this.categoryType = categoryType;
    }

    @Override
    public String toString() {
        return "ProductCategory{" +
                "categoryId=" + categoryId +
                ", categoryName='" + categoryName + ''' +
                ", categoryType=" + categoryType +
                '}';
    }
}

是不是長的過分?OK,現在開始操作。

現在pom.xml中引入Lombok

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

引入完之後一定要記得Maven重新Import Changes
引入完之後一定要記得Maven重新Import Changes
引入完之後一定要記得Maven重新Import Changes


接下來,如果是Idea的使用者,我們需要安裝一個Lombok外掛,才能有語法提示

OK,最後,在我們剛剛的那個實體上加code>@Data註解。意為自動生成GetterSettertoString等。然後愉快的把所有多餘的代碼刪除吧。

代碼:

@Entity
@DynamicUpdate//動態更新
@Data
public class ProductCategory {
    /**
     * 類目id
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer categoryId;

    /**
     * 類目名字
     */
    private String categoryName;

    /**
     * 類目編號
     */
    private Integer categoryType;

    private  Date createTime;

    private  Date updateTime;

}

只有實體屬性,非常乾淨。至於性能問題,lombok生成的GetterSetter等,是在編譯期加入的,所以不影響性能。

Recent Posts

Flexible Shipping Pro

在WordPress的世界裡,…

4天 ago

2023 年 WordPress 中最棒的多語言翻譯外掛推薦

擔心如何翻譯您的網站語言以支持…

1年 ago

2023 年 WordPress 中最棒的可視化頁面構建器外掛推薦

在設計任何頁面或網站時,對於不…

1年 ago

Ella 多用途 Shopify 佈景主題

Shopify 佈景主題市場上有許…

1年 ago

AI Engine Pro

喵容今天帶來的 AI Engi…

1年 ago

AIKit

喵容今天為您帶來 AIKit …

1年 ago