Lombok註解筆記

lombok版本:1.18.2

前言

把lombok的註解過了一遍,發現有個@ExtensionMethod和kotlin的拓展函數有點相似java

註解

@AllArgsConstructor

做用

生成包含全部字段的構造器maven

參數
  • staticName : 不爲空的話,生成一個靜態方法返回實例,並把構造器設置爲private
@AllArgsConstructor(staticName = "create")
public class Example {

    private int foo;
    private final String bar;
}

生成:函數

public class Example {
    private int foo;
    private final String bar;

    private Example(int foo, String bar) {
        this.foo = foo;
        this.bar = bar;
    }

    public static Example create(int foo, String bar) {
        return new Example(foo, bar);
    }
}
  • access : 構造器訪問權限修飾符,默認public

@Builder

做用

生成構建者(Builder)模式測試

例子:
@Builder
public class Example {

    private int foo;
    private final String bar;
}

生成:ui

public class Example {
    private int foo;
    private final String bar;

    Example(int foo, String bar) {
        this.foo = foo;
        this.bar = bar;
    }

    public static Example.ExampleBuilder builder() {
        return new Example.ExampleBuilder();
    }

    public static class ExampleBuilder {
        private int foo;
        private String bar;

        ExampleBuilder() {
        }

        public Example.ExampleBuilder foo(int foo) {
            this.foo = foo;
            return this;
        }

        public Example.ExampleBuilder bar(String bar) {
            this.bar = bar;
            return this;
        }

        public Example build() {
            return new Example(this.foo, this.bar);
        }

        public String toString() {
            return "Example.ExampleBuilder(foo=" + this.foo + ", bar=" + this.bar + ")";
        }
    }
}
參數
  • builderMethodName : 建立構建器實例的方法名稱
  • buildMethodName:構建器類中建立構造器實例的方法名稱
  • builderClassName:構造器類名
  • toBuilder:生成toBuilder方法
例子
public Example.ExampleBuilder toBuilder() {
    return (new Example.ExampleBuilder()).foo(this.foo).bar(this.bar);
}

@Cleanup

做用

在變量上聲明@Cleanup,生成的代碼會把變量用try{}包圍,並在finallly塊中調用close()this

例子
public class Example {

    public void copyFile(String in, String out) throws IOException {
        @Cleanup FileInputStream inStream = new FileInputStream(in);
        @Cleanup FileOutputStream outStream = new FileOutputStream(out);
        byte[] b = new byte[65536];
        while (true) {
            int r = inStream.read(b);
            if (r == -1) break;
            outStream.write(b, 0, r);
        }
    }
}

生成後:代理

public class Example {
    public Example() {
    }

    public void copyFile(String in, String out) throws IOException {
        FileInputStream inStream = new FileInputStream(in);

        try {
            FileOutputStream outStream = new FileOutputStream(out);

            try {
                byte[] b = new byte[65536];

                while(true) {
                    int r = inStream.read(b);
                    if (r == -1) {
                        return;
                    }

                    outStream.write(b, 0, r);
                }
            } finally {
                if (Collections.singletonList(outStream).get(0) != null) {
                    outStream.close();
                }

            }
        } finally {
            if (Collections.singletonList(inStream).get(0) != null) {
                inStream.close();
            }

        }
    }
}
參數
  • value:被在finally塊中調用的方法名,方法體不能帶有參數,默認爲close

@Data

做用

生成全部字段的getter、toString()、hashCode()、equals()、全部非final字段的setter、構造器,至關於設置了 @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCodecode

例子
@Data
public class Example {

    private int foo;
    private final String bar;
}

生成:文檔

public class Example {
    private int foo;
    private final String bar;

    public Example(String bar) {
        this.bar = bar;
    }

    public int getFoo() {
        return this.foo;
    }

    public String getBar() {
        return this.bar;
    }

    public void setFoo(int foo) {
        this.foo = foo;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof Example)) {
            return false;
        } else {
            Example other = (Example)o;
            if (!other.canEqual(this)) {
                return false;
            } else if (this.getFoo() != other.getFoo()) {
                return false;
            } else {
                Object this$bar = this.getBar();
                Object other$bar = other.getBar();
                if (this$bar == null) {
                    if (other$bar != null) {
                        return false;
                    }
                } else if (!this$bar.equals(other$bar)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof Example;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        int result = result * 59 + this.getFoo();
        Object $bar = this.getBar();
        result = result * 59 + ($bar == null ? 43 : $bar.hashCode());
        return result;
    }

    public String toString() {
        return "Example(foo=" + this.getFoo() + ", bar=" + this.getBar() + ")";
    }
}

@Delegate

@EqualsAndHashCode

做用

生成hashCode()、equals(),效果見@Dataget

參數
  • callSuper:是否調用父類的hashCode(),默認:false
  • doNotUseGetters:是否不調用字段的getter,默認若是有getter會調用。設置爲true,直接訪問字段,不調用getter
  • exclude:此處列出的任何字段都不會在生成的equals和hashCode中使用。
  • of:與exclude相反,設置of,exclude失效
  • onParam:添加註解,參考@Getter#onMethod

@Generated

做用

這個註解彷佛沒有實在的做用,就是標記這個類、字段、方法是自動生成的

@Getter

做用

生成getter、寫在類上會生成該類下全部字段的getter。寫在某個字段上就做用與該字段

參數
  • onMethod:把須要添加的註解寫在這
例子
public class Example {

    @Getter(onMethod_={@Deprecated}) // JDK7寫法 @Getter(onMethod=@__({@Deprecated}))
    private int foo;
    private final String bar  = "";
}

生成:

public class Example {
    private int foo;
    private final String bar = "";

    public Example() {
    }

    /** @deprecated */
    @Deprecated
    public int getFoo() {
        return this.foo;
    }
}
  • value:訪問權限修飾符

@NoArgsConstructor

做用

生成無參數構造器

參數
  • access:訪問權限修飾符
  • force:爲true時,強制生成構造器,final字段初始化爲null
  • onConstructor:添加註解,參考@Getter#onMethod

@NonNull

做用

空檢查

例子
public class Example {

    @NonNull
    @Getter
    @Setter
    private Integer foo;
}

生成後:

public class Example {
    @NonNull
    private Integer foo;

    public Example() {
    }

    @NonNull
    public Integer getFoo() {
        return this.foo;
    }

    public void setFoo(@NonNull Integer foo) {
        if (foo == null) {
            throw new NullPointerException("foo is marked @NonNull but is null");
        } else {
            this.foo = foo;
        }
    }
}

@RequiredArgsConstructor

做用

生成必須初始化字段的構造器,好比帶final、@NonNull

例子
@RequiredArgsConstructor
public class Example {

    @NonNull
    private Integer foo;
    private final String bar;
}

生成後:

public class Example {
    @NonNull
    private Integer foo;
    private final String bar;

    public Example(@NonNull Integer foo, String bar) {
        if (foo == null) {
            throw new NullPointerException("foo is marked @NonNull but is null");
        } else {
            this.foo = foo;
            this.bar = bar;
        }
    }
}

@Setter

做用

生成Setter

參數
  • onMethod:在方法上添加中註解,見@Getter#onMethod
  • onParam:在方法的參數上添加註解,見@Getter#onMethod
  • value:訪問權限修飾符

@Singular

做用

這個註解和@Builder一塊兒使用,爲Builder生成字段是集合類型的add方法,字段名不能是單數形式,不然須要指定value值

例子
@Builder
public class Example {

    @Singular
    @Setter
    private List<Integer> foos;
}

生成:

public class Example {
    private List<Integer> foos;

    Example(List<Integer> foos) {
        this.foos = foos;
    }

    public static Example.ExampleBuilder builder() {
        return new Example.ExampleBuilder();
    }

    public void setFoos(List<Integer> foos) {
        this.foos = foos;
    }

    public static class ExampleBuilder {
        private ArrayList<Integer> foos;

        ExampleBuilder() {
        }
        
        // 這方法是@Singular做用生成的
        public Example.ExampleBuilder foo(Integer foo) {
            if (this.foos == null) {
                this.foos = new ArrayList();
            }

            this.foos.add(foo);
            return this;
        }

        public Example.ExampleBuilder foos(Collection<? extends Integer> foos) {
            if (this.foos == null) {
                this.foos = new ArrayList();
            }

            this.foos.addAll(foos);
            return this;
        }

        public Example.ExampleBuilder clearFoos() {
            if (this.foos != null) {
                this.foos.clear();
            }

            return this;
        }

        public Example build() {
            List foos;
            switch(this.foos == null ? 0 : this.foos.size()) {
            case 0:
                foos = Collections.emptyList();
                break;
            case 1:
                foos = Collections.singletonList(this.foos.get(0));
                break;
            default:
                foos = Collections.unmodifiableList(new ArrayList(this.foos));
            }

            return new Example(foos);
        }

        public String toString() {
            return "Example.ExampleBuilder(foos=" + this.foos + ")";
        }
    }
}

@SneakyThrows

做用

用try{}catch{}捕捉異常

例子
public class Example {

    @SneakyThrows(UnsupportedEncodingException.class)
    public String utf8ToString(byte[] bytes) {
        return new String(bytes, "UTF-8");
    }
}

生成後:

public class Example {
    public Example() {
    }

    public String utf8ToString(byte[] bytes) {
        try {
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException var3) {
            throw var3;
        }
    }
}

@Synchronized

做用

生成Synchronized(){}包圍代碼

例子
public class Example {

    @Synchronized
    public String utf8ToString(byte[] bytes) {
        return new String(bytes, Charset.defaultCharset());
    }
}

生成後:

public class Example {
    private final Object $lock = new Object[0];

    public Example() {
    }

    public String utf8ToString(byte[] bytes) {
        Object var2 = this.$lock;
        synchronized(this.$lock) {
            return new String(bytes, Charset.defaultCharset());
        }
    }
}

@ToString

做用

生成toString()方法

@val

做用

變量聲明類型推斷

例子
public class ValExample {
    public String example() {
        val example = new ArrayList<String>();
        example.add("Hello, World!");
        val foo = example.get(0);
        return foo.toLowerCase();
    }

    public void example2() {
        val map = new HashMap<Integer, String>();
        map.put(0, "zero");
        map.put(5, "five");
        for (val entry : map.entrySet()) {
            System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
        }
    }
}

生成後:

public class ValExample {
    public ValExample() {
    }

    public String example() {
        ArrayList<String> example = new ArrayList();
        example.add("Hello, World!");
        String foo = (String)example.get(0);
        return foo.toLowerCase();
    }

    public void example2() {
        HashMap<Integer, String> map = new HashMap();
        map.put(0, "zero");
        map.put(5, "five");
        Iterator var2 = map.entrySet().iterator();

        while(var2.hasNext()) {
            Entry<Integer, String> entry = (Entry)var2.next();
            System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
        }

    }
}

@Value

做用

把類聲明爲final,並添加toString()、hashCode()等方法,至關於 @Getter @FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE) @AllArgsConstructor @ToString @EqualsAndHashCode.

例子
@Value
public class Example {

    private Integer foo;
}

生成後:

public final class Example {
    private final Integer foo;

    public Example(Integer foo) {
        this.foo = foo;
    }

    public Integer getFoo() {
        return this.foo;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof Example)) {
            return false;
        } else {
            Example other = (Example)o;
            Object this$foo = this.getFoo();
            Object other$foo = other.getFoo();
            if (this$foo == null) {
                if (other$foo != null) {
                    return false;
                }
            } else if (!this$foo.equals(other$foo)) {
                return false;
            }

            return true;
        }
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $foo = this.getFoo();
        int result = result * 59 + ($foo == null ? 43 : $foo.hashCode());
        return result;
    }

    public String toString() {
        return "Example(foo=" + this.getFoo() + ")";
    }
}

@var

做用

和val同樣,官方文檔中說區別就是var不加final修飾,但測試的效果是同樣的

Experimental註解

在lombok.experimental包下

@Accessors

做用

默認狀況下,沒什麼做用,須要設置參數

參數
  • chain:爲true時,setter鏈式返回,即setter的返回值爲this
  • fluent:爲true時,默認設置chain爲true,setter的方法名修改成字段名

@Delegate

做用

代理模式,把字段的方法代理給類,默認代理全部方法

參數
  • types:指定代理的方法
  • excludes:和types相反
例子
public class Example {

    private interface Add {
        boolean add(String x);
        boolean addAll(Collection<? extends String> x);
    }

    private @Delegate(types = Add.class) List<String> strings;
}

生成後:

public class Example {
    private List<String> strings;

    public Example() {
    }

    public boolean add(String x) {
        return this.strings.add(x);
    }

    public boolean addAll(Collection<? extends String> x) {
        return this.strings.addAll(x);
    }

    private interface Add {
        boolean add(String var1);

        boolean addAll(Collection<? extends String> var1);
    }
}

@ExtensionMethod

做用

拓展方法,向現有類型「添加」方法,而無需建立新的派生類型。有點像kotlin的擴展函數。

例子
@ExtensionMethod({Arrays.class, Extensions.class})
public class Example {

    public static void main(String[] args) {
        int[] intArray = {5, 3, 8, 2};
        intArray.sort();
        int num = 1;
        num = num.increase();

        Arrays.stream(intArray).forEach(System.out::println);
        System.out.println("num = " + num);
    }
}

class Extensions {
    public static int increase(int num) {
        return ++num;
    }
}

生成後:

public class Example {
    public Example() {
    }

    public static void main(String[] args) {
        int[] intArray = new int[]{5, 3, 8, 2};
        Arrays.sort(intArray);
        int num = 1;
        int num = Extensions.increase(num);
        IntStream var10000 = Arrays.stream(intArray);
        PrintStream var10001 = System.out;
        System.out.getClass();
        var10000.forEach(var10001::println);
        System.out.println("num = " + num);
    }
}

輸出:

2
3
5
8
num = 2

@FieldDefaults

做用

定義類、字段的修飾符

參數
  • AccessLevel:訪問權限修飾符
  • makeFinal:是否加final

@FieldNameConstants

做用

默認生成一個常量,名稱爲大寫字段名,值爲字段名

參數
  • prefix:前綴
  • suffix:後綴
例子
public class Example {

    @FieldNameConstants(prefix = "PREFIX_", suffix = "_SUFFIX")
    private String foo;
}

生成後:

public class Example {
    public static final String PREFIX_FOO_SUFFIX = "foo";
    private String foo;

    public Example() {
    }
}

@Helper

做用

方法內部的類方法暴露給方法使用

測試時,maven編譯不經過。

@NonFinal

做用

設置不爲Final,@FieldDefaults和@Value也有這功能

@PackagePrivate

做用

設置爲private,@FieldDefaults和@Value也有這功能

@SuperBuilder

@Tolerate

@UtilityClass

@Wither

做用

生成withXXX方法,返回類實例

例子
@RequiredArgsConstructor
public class Example {
    private @Wither final int foo;
}

生成後:

public class Example {
    private final int foo;

    public Example(int foo) {
        this.foo = foo;
    }

    public Example withFoo(int foo) {
        return this.foo == foo ? this : new Example(foo);
    }
}
相關文章
相關標籤/搜索