Lombok注解笔记

1,449 阅读5分钟
原文链接: segmentfault.com
lombok版本:1.18.2

前言

把lombok的注解过了一遍,发现有个@ExtensionMethod和kotlin的拓展函数有点类似

注解

@AllArgsConstructor

作用

生成包含所有字段的构造器

参数
  • 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;
}

生成:

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()

例子
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 @EqualsAndHashCode

例子
@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(),效果见@Data

参数
  • 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);
    }
}