簡體   English   中英

Intellij Idea自動創建課程的鏈接設置器

[英]Intellij Idea automatic creation of chaining setters for class

我在類似以下的類中創建受邀的setter:

public class Example {
    private String name;
    private Integer id;

    ...

    public Example withName(String name) {
        this.name = name;
        return this;
    }
    public Example withID(Integer id) {
        this.id = id;
        return this;
    }
    ...
}

因此實例的初始化變得更加清晰(您可以看到已設置的字段,而無需重復實例名稱):

Example example = 
    new Example()
            .withName("Walter")
            .withID(23);

是否具有重構/代碼約束方法來自動構建類的鏈初始化?

您可以使用Code | Generate... Code | Generate...以自動創建二傳手。 首先將字段添加到類中:

class Example {
    private String name;
    private Integer id;
}

現在調用Code | Generate... Code | Generate... (在Mac上為Cmd + N ),然后選擇Setter 在出現的對話框頂部選擇模板Builder 選擇要為其生成設置器的字段,然后單擊“ OK 結果:

class Example {
    private String name;
    private Integer id;

    public Example setName(String name) {
        this.name = name;
        return this;
    }

    public Example setId(Integer id) {
        this.id = id;
        return this;
    }
}

如果你想setter方法開始與with而不是set ,它是可以修改的模板。

  1. 首先,生成帶有字段的構造函數。
  2. 然后右鍵單擊選擇“重構”,然后用構造器替換構造器。

     Example e=new ExampleBuilder().setId(1).setName("name").createExample(); 

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM