资讯专栏INFORMATION COLUMN

Lombok注解笔记

shery / 1690人阅读

摘要:设置为,直接访问字段,不调用此处列出的任何字段都不会在生成的和中使用。与相反,设置,失效添加注解,参考作用这个注解似乎没有实在的作用,就是标记这个类字段方法是自动生成的作用生成写在类上会生成该类下所有字段的。有点像的扩展函数。

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 foos;
}

生成:

public class Example {
    private List foos;

    Example(List foos) {
        this.foos = foos;
    }

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

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

    public static class ExampleBuilder {
        private ArrayList 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 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();
        example.add("Hello, World!");
        val foo = example.get(0);
        return foo.toLowerCase();
    }

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

生成后:

public class ValExample {
    public ValExample() {
    }

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

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

        while(var2.hasNext()) {
            Entry entry = (Entry)var2.next();
            System.out.printf("%d: %s
", 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 x);
    }

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

生成后:

public class Example {
    private List strings;

    public Example() {
    }

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

    public boolean addAll(Collection x) {
        return this.strings.addAll(x);
    }

    private interface Add {
        boolean add(String var1);

        boolean addAll(Collection 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);
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76816.html

相关文章

  • Java 编译器 javac 笔记:javac API、注解处理 API 与 Lombok 原理

    摘要:对语法树的扫描,同样提供了扫描器。词法分析过程如下图所示语法分析,即根据语法由序列生成抽象语法树,对应实现类为。生成的抽象语法树如下图所示的实现原理依赖开发的典型的第三方库有,代码自动生成的和,代码检查的和,编译阶段完成依赖注入的等。 原文:http://nullwy.me/2017/04/java...如果觉得我的文章对你有用,请随意赞赏 javac 是 Java 代码的编译器 [...

    lookSomeone 评论0 收藏0
  • 使用 lombok 简化 Java 代码

    摘要:使用可以大大减少代码行数,提高开发效率。提供了日志工具无参构造器提供方法提供方法方法有参构造器,参数按属性定义顺序传入提供了空指针检测,会抛出异常 lombok 是一个第三方工具,提供了一些注解功能,可以帮助我们消除冗余、臃肿的 Java 代码,比如 POJO 的 getter/setter 方法、构造方法、hashcode 方法等。lombok 在编译时根据注解生成具体的代码,在虚拟...

    CloudwiseAPM 评论0 收藏0
  • 第二十九章:基于SpringBoot平台使用Lombok来优雅的编码

    摘要:还提供了全部参数的构造函数的自动生成,该注解的作用域也是只有在实体类上,因为只有实体类才会存在构造函数。当然除了全部参数的构造函数,还提供了没有参数的构造函数,使用方式与一致。 Lombok对于Java偷懒开发者来说应该是比较中意的,恰恰笔者就是一个喜欢在小细节上偷懒来提高开发效率的人。所以在技术框架的海洋里寻找了很久才在GitHub开源平台上找到,而在这之前国外很多程序猿一直使用该框...

    fanux 评论0 收藏0
  • Lombok安装及Spring Boot集成Lombok

    摘要:注意,其是在编译源码过程中,帮你自动生成的。就是说,将极大减少你的代码总量。注解和类似,区别在于它会把所有成员变量默认定义为修饰,并且不会生成方法。不同的日志注解总结如下上面是注解,下面是编译后的代码参考资料下的安装以及使用简介注解介绍 Lombok有什么用 在我们实体Bean中有大量的Getter/Setter方法以及toString, hashCode等可能不会用到,但是某些时候仍...

    dkzwm 评论0 收藏0
  • Lombok 看这篇就够了

    摘要:注解在类上为类提供一个全参的构造方法,加了这个注解后,类中不提供默认构造方法了。这个注解用在类上,使用类中所有带有注解的或者带有修饰的成员变量生成对应的构造方法。 转载请注明原创地址:http://www.54tianzhisheng.cn/2018/01/07/lombok/ showImg(http://ohfk1r827.bkt.clouddn.com/blog/180107/7...

    LeanCloud 评论0 收藏0

发表评论

0条评论

shery

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<