LomBok特性学习与使用

1. val--自动生成泛型类的真实的数据类型

源码:

package com.test.lombok.val;

import lombok.val;

import java.util.ArrayList;
import java.util.HashMap;

public class LomBokVal {
    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 static void main(String[] args){
        LomBokVal lomBokVal = new LomBokVal();

        System.out.println(lomBokVal.example());
        lomBokVal.example2();
    }
}
View Code

编译后生成的class文件:

package com.test.lombok.val;

import lombok.val;

import java.util.ArrayList;
import java.util.HashMap;

public class LomBokVal {
    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 static void main(String[] args){
        LomBokVal lomBokVal = new LomBokVal();

        System.out.println(lomBokVal.example());
        lomBokVal.example2();
    }
}
View Code

2. var--自动生成泛型类的真实的数据类型

默认情况下该功能不启用,需要在配置文件lombok.config中进行配置:

源码:

package com.test.lombok.var;

import lombok.experimental.var;

import java.util.ArrayList;
import java.util.HashMap;

public class LomBokVar {
    public String example() {
        var example = new ArrayList<String>();
        example.add("hello world!");
        var foo = example.get(0);
        return foo.toLowerCase();
    }

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

    public static void main(String[] args) {
        LomBokVar lomBokVar = new LomBokVar();

        System.out.println(lomBokVar.example());
        lomBokVar.example2();
    }
}
View Code

编译后生成的class文件:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.var;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class LomBokVar {
    public LomBokVar() {
    }

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

    }

    public static void main(String[] args) {
        LomBokVar lomBokVar = new LomBokVar();
        System.out.println(lomBokVar.example());
        lomBokVar.example2();
    }
}
View Code

3. @NonNull--自动生成非空校验,默认抛出NullPointerException异常

源码:

package com.test.lombok.NonNull;

import lombok.NonNull;

public class LomBokNonNull {
    public void example(@NonNull String name) {
        System.out.println("hello, " + name);
    }

    public static void main(String[] args) {
        LomBokNonNull lomBokNonNull = new LomBokNonNull();
        lomBokNonNull.example("test");
        try {
            lomBokNonNull.example(null);
        } catch (NullPointerException e) {
            System.out.println("param is not allowed to be null");
        }

    }
}
View Code

生成的class文件:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.NonNull;

import lombok.NonNull;

public class LomBokNonNull {
    public LomBokNonNull() {
    }

    public void example(@NonNull String name) {
        if (name == null) {
            throw new NullPointerException("name");
        } else {
            System.out.println("hello, " + name);
        }
    }

    public static void main(String[] args) {
        LomBokNonNull lomBokNonNull = new LomBokNonNull();
        lomBokNonNull.example("test");

        try {
            lomBokNonNull.example((String)null);
        } catch (NullPointerException var3) {
            System.out.println("param is not allowed to be null");
        }

    }
}
View Code

可以在配置文件中配置抛出的异常类型:

lombok.nonNull.exceptionType = [NullPointerException | IllegalArgumentException] (默认: NullPointerException).

即使代码中存在null值的判断,仍会自动生成非空判断:

// 源码
package com.test.lombok.NonNull;

import lombok.NonNull;

public class LomBokNonNull {
    public void example(@NonNull String name) {
        System.out.println("NonNull test start");
        if (name == null)
        {
            System.out.println("hello, stranger");
            return;
        }
        System.out.println("hello, " + name);
    }

    public static void main(String[] args) {
        LomBokNonNull lomBokNonNull = new LomBokNonNull();
        lomBokNonNull.example("test");
        try {
            lomBokNonNull.example(null);
        } catch (NullPointerException e) {
            System.out.println("param is not allowed to be null");
        }

    }
}

// 生成的class文件
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.NonNull;

import lombok.NonNull;

public class LomBokNonNull {
    public LomBokNonNull() {
    }

    public void example(@NonNull String name) {
        if (name == null) {
            throw new NullPointerException("name");
        } else {
            System.out.println("NonNull test start");
            if (name == null) {
                System.out.println("hello, stranger");
            } else {
                System.out.println("hello, " + name);
            }
        }
    }

    public static void main(String[] args) {
        LomBokNonNull lomBokNonNull = new LomBokNonNull();
        lomBokNonNull.example("test");

        try {
            lomBokNonNull.example((String)null);
        } catch (NullPointerException var3) {
            System.out.println("param is not allowed to be null");
        }

    }
}
View Code

4. @Cleanup--资源的自动管理

如果需要释放的资源没有对应的close方法,而是用其他的方法进行资源的释放,可以使用@Cleanup("methodName")来指明需要调用的方法名称

// 源码:
package com.test.lombok.cleanup;

import lombok.Cleanup;

import java.io.*;

public class LomBokCleanup {
    public static void main(String[] args) throws IOException {
        @Cleanup InputStream in = new FileInputStream(args[0]);
        @Cleanup OutputStream out = new FileOutputStream(args[1]);
        byte[] b = new byte[10000];
        while (true) {
            int r = in.read(b);
            if (r == -1) break;
            out.write(b, 0, r);
        }
    }
}

// 生成的class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.cleanup;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;

public class LomBokCleanup {
    public LomBokCleanup() {
    }

    public static void main(String[] args) throws IOException {
        FileInputStream in = new FileInputStream(args[0]);

        try {
            FileOutputStream out = new FileOutputStream(args[1]);

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

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

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

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

        }
    }
}
View Code

5. @Getter/@Setter--生成get和set方法

// 源码:
package com.test.lombok.getterAndSetter;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

public class LomBokGettertAndSetter {
    @Getter
    @Setter
    private int age = 10;

    @Setter(AccessLevel.PROTECTED)
    private String name;

    @Override
    public String toString() {
        return String.format("%s (age: %d)", name, age);
    }

    public static void main(String[] args) {
        LomBokGettertAndSetter lomBokGettertAndSetter = new LomBokGettertAndSetter();
        lomBokGettertAndSetter.setName("test");
        lomBokGettertAndSetter.setAge(10);
        System.out.println(lomBokGettertAndSetter.getAge());
        System.out.println(lomBokGettertAndSetter.toString());
    }
}

// 生成的class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.getterAndSetter;

public class LomBokGettertAndSetter {
    private int age = 10;
    private String name;

    public LomBokGettertAndSetter() {
    }

    public String toString() {
        return String.format("%s (age: %d)", this.name, this.age);
    }

    public static void main(String[] args) {
        LomBokGettertAndSetter lomBokGettertAndSetter = new LomBokGettertAndSetter();
        lomBokGettertAndSetter.setName("test");
        lomBokGettertAndSetter.setAge(10);
        System.out.println(lomBokGettertAndSetter.getAge());
        System.out.println(lomBokGettertAndSetter.toString());
    }

    public int getAge() {
        return this.age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    protected void setName(String name) {
        this.name = name;
    }
}
View Code

6. ToString--自动重写toString方法

// 源码:
package com.test.lombok.toString;

import lombok.ToString;

// exclude指出不在toString方法中打印出来的属性的名称
@ToString(exclude = "id")
public class LomBokToString {
    private static String excludeString = "exclude string";
    private int id;
    private String name;
    private String[] tags;
    private Shape shape = new Square(4, 5);

    public static class Shape {

    }

    // callSuper标志是否调用父类的toString方法,includeFieldNames标志是否显示属性名称
    @ToString(callSuper = false, includeFieldNames = true)
    public static class Square extends Shape {
        private final int width, height;

        public Square(int width, int height) {
            this.width = width;
            this.height = height;
        }
    }

    public static void main(String[] args) {
        LomBokToString lomBokToString = new LomBokToString();
        System.out.println(lomBokToString.toString());
    }
}

// 生成的class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.toString;

import java.util.Arrays;

public class LomBokToString {
    private static String excludeString = "exclude string";
    private int id;
    private String name;
    private String[] tags;
    private LomBokToString.Shape shape = new LomBokToString.Square(4, 5);

    public LomBokToString() {
    }

    public static void main(String[] args) {
        LomBokToString lomBokToString = new LomBokToString();
        System.out.println(lomBokToString.toString());
    }

    public String toString() {
        return "LomBokToString(name=" + this.name + ", tags=" + Arrays.deepToString(this.tags) + ", shape=" + this.shape + ")";
    }

    public static class Square extends LomBokToString.Shape {
        private final int width;
        private final int height;

        public Square(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public String toString() {
            return "LomBokToString.Square(width=" + this.width + ", height=" + this.height + ")";
        }
    }

    public static class Shape {
        public Shape() {
        }
    }
}
View Code

7. @EuqalsAndHashCode--自动生成equals和hashcode方法(static和transient属性除外)

// 源码:
package com.test.lombok.equalsAndHashCode;

import lombok.EqualsAndHashCode;

// exclude表示在equals和hashcode方法总不使用该属性
@EqualsAndHashCode(exclude = {"id", "shape"})
public class LomBokEqualsAndHashCode {
    private transient int transientVar = 10;
    private static String excludeString = "exclude string";
    private int id;
    private String name;
    private double score;
    private String[] tags;
    private Shape shape = new Square(4, 5);

    public static class Shape {

    }

    // callSuper标志是否调用父类的equals和hashcode方法
    @EqualsAndHashCode(callSuper = true)
    public static class Square extends Shape {
        private final int width, height;

        public Square(int width, int height) {
            this.width = width;
            this.height = height;
        }
    }

    public static void main(String[] args) {
        LomBokEqualsAndHashCode lomBokEqualsAndHashCode1 = new LomBokEqualsAndHashCode();
        lomBokEqualsAndHashCode1.id = 1;

        LomBokEqualsAndHashCode lomBokEqualsAndHashCode2 = new LomBokEqualsAndHashCode();
        lomBokEqualsAndHashCode1.id = 2;

        System.out.println(lomBokEqualsAndHashCode1.equals(lomBokEqualsAndHashCode2));
    }
}

// class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.equalsAndHashCode;

import java.util.Arrays;

public class LomBokEqualsAndHashCode {
    private transient int transientVar = 10;
    private static String excludeString = "exclude string";
    private int id;
    private String name;
    private double score;
    private String[] tags;
    private LomBokEqualsAndHashCode.Shape shape = new LomBokEqualsAndHashCode.Square(4, 5);

    public LomBokEqualsAndHashCode() {
    }

    public static void main(String[] args) {
        LomBokEqualsAndHashCode lomBokEqualsAndHashCode1 = new LomBokEqualsAndHashCode();
        lomBokEqualsAndHashCode1.id = 1;
        LomBokEqualsAndHashCode lomBokEqualsAndHashCode2 = new LomBokEqualsAndHashCode();
        lomBokEqualsAndHashCode1.id = 2;
        System.out.println(lomBokEqualsAndHashCode1.equals(lomBokEqualsAndHashCode2));
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof LomBokEqualsAndHashCode)) {
            return false;
        } else {
            LomBokEqualsAndHashCode other = (LomBokEqualsAndHashCode)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                label31: {
                    Object this$name = this.name;
                    Object other$name = other.name;
                    if (this$name == null) {
                        if (other$name == null) {
                            break label31;
                        }
                    } else if (this$name.equals(other$name)) {
                        break label31;
                    }

                    return false;
                }

                if (Double.compare(this.score, other.score) != 0) {
                    return false;
                } else {
                    return Arrays.deepEquals(this.tags, other.tags);
                }
            }
        }
    }

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

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $name = this.name;
        int result = result * 59 + ($name == null ? 43 : $name.hashCode());
        long $score = Double.doubleToLongBits(this.score);
        result = result * 59 + (int)($score >>> 32 ^ $score);
        result = result * 59 + Arrays.deepHashCode(this.tags);
        return result;
    }

    public static class Square extends LomBokEqualsAndHashCode.Shape {
        private final int width;
        private final int height;

        public Square(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public boolean equals(Object o) {
            if (o == this) {
                return true;
            } else if (!(o instanceof LomBokEqualsAndHashCode.Square)) {
                return false;
            } else {
                LomBokEqualsAndHashCode.Square other = (LomBokEqualsAndHashCode.Square)o;
                if (!other.canEqual(this)) {
                    return false;
                } else if (!super.equals(o)) {
                    return false;
                } else if (this.width != other.width) {
                    return false;
                } else {
                    return this.height == other.height;
                }
            }
        }

        protected boolean canEqual(Object other) {
            return other instanceof LomBokEqualsAndHashCode.Square;
        }

        public int hashCode() {
            int PRIME = true;
            int result = super.hashCode();
            result = result * 59 + this.width;
            result = result * 59 + this.height;
            return result;
        }
    }

    public static class Shape {
        public Shape() {
        }
    }
}
View Code

8. @NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor--自动生成构造函数

// 源码:
package com.test.lombok.constructor;

import lombok.*;

// 当class中包含final修饰的属性时,属性必须进行初始化,否则使用@NoArgsConstructor时将会出现错误,
// 需要使用@NoArgsConstructor(force = true)对未初始化的数据进行强制初始化为0/false/null
// 若该属性使用@NonNull进行标记,将不会生成null检查
@NoArgsConstructor(force = true)
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class LomBokConstructor {
    private final int id;
    private int x,y;
    @NonNull private String name;
}

// 生成的class文件
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.constructor;

import lombok.NonNull;

public class LomBokConstructor {
    private final int id;
    private int x;
    private int y;
    @NonNull
    private String name;

    public LomBokConstructor() {
        this.id = 0;
    }

    private LomBokConstructor(int id, @NonNull String name) {
        if (name == null) {
            throw new NullPointerException("name");
        } else {
            this.id = id;
            this.name = name;
        }
    }

    public static LomBokConstructor of(int id, @NonNull String name) {
        return new LomBokConstructor(id, name);
    }

    protected LomBokConstructor(int id, int x, int y, @NonNull String name) {
        if (name == null) {
            throw new NullPointerException("name");
        } else {
            this.id = id;
            this.x = x;
            this.y = y;
            this.name = name;
        }
    }
}
View Code

9. @Data

//源码:
package com.test.lombok.data;

import lombok.AccessLevel;
import lombok.Data;
import lombok.NonNull;
import lombok.Setter;

/**
 * @ToString, @EqualsAndHashCode, 所有属性@Getter, 所有非final属性@Setter, @RequiredArgsConstructor的简写
 * @Data 无法使用相关注解的属性
 */
@Data(staticConstructor = "of")
public class LomBokData {

    private int id;
    @NonNull private String name;
    @Setter(AccessLevel.PACKAGE) private int age;
}

// 生成的class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.data;

import lombok.NonNull;

public class LomBokData {
    private int id;
    @NonNull
    private String name;
    private int age;

    private LomBokData(@NonNull String name) {
        if (name == null) {
            throw new NullPointerException("name");
        } else {
            this.name = name;
        }
    }

    public static LomBokData of(@NonNull String name) {
        return new LomBokData(name);
    }

    public int getId() {
        return this.id;
    }

    @NonNull
    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(@NonNull String name) {
        if (name == null) {
            throw new NullPointerException("name");
        } else {
            this.name = name;
        }
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof LomBokData)) {
            return false;
        } else {
            LomBokData other = (LomBokData)o;
            if (!other.canEqual(this)) {
                return false;
            } else if (this.getId() != other.getId()) {
                return false;
            } else {
                Object this$name = this.getName();
                Object other$name = other.getName();
                if (this$name == null) {
                    if (other$name == null) {
                        return this.getAge() == other.getAge();
                    }
                } else if (this$name.equals(other$name)) {
                    return this.getAge() == other.getAge();
                }

                return false;
            }
        }
    }

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

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

    public String toString() {
        return "LomBokData(id=" + this.getId() + ", name=" + this.getName() + ", age=" + this.getAge() + ")";
    }

    void setAge(int age) {
        this.age = age;
    }
}
View Code

10. @Value

// 源码:
package com.test.lombok.value;

import lombok.ToString;
import lombok.Value;
import lombok.experimental.NonFinal;
import lombok.experimental.Tolerate;

/**
 * @Value 相当于final @ToString @EqualsAndHashCode 
 * @AllArgsConstructor @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @Getter的简写
 */
@Value(staticConstructor = "of")
public class LomBokValue {
    String name;
    @NonFinal
    int age;
    double score;
    protected String[] tags;

    @Tolerate
    public LomBokValue(String name, double score, String[] tags) {
        this.name = name;
        this.score = score;
        this.tags = tags;
    }

    @ToString(includeFieldNames=true)
    @Value(staticConstructor="of")
    public static class Exercise<T> {
        String name;
        T value;
    }
}

// 生成的class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.value;

import java.util.Arrays;

public final class LomBokValue {
    private final String name;
    private int age;
    private final double score;
    protected final String[] tags;

    public LomBokValue(String name, double score, String[] tags) {
        this.name = name;
        this.score = score;
        this.tags = tags;
    }

    private LomBokValue(String name, int age, double score, String[] tags) {
        this.name = name;
        this.age = age;
        this.score = score;
        this.tags = tags;
    }

    public static LomBokValue of(String name, int age, double score, String[] tags) {
        return new LomBokValue(name, age, score, tags);
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }

    public double getScore() {
        return this.score;
    }

    public String[] getTags() {
        return this.tags;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof LomBokValue)) {
            return false;
        } else {
            LomBokValue other = (LomBokValue)o;
            Object this$name = this.getName();
            Object other$name = other.getName();
            if (this$name == null) {
                if (other$name != null) {
                    return false;
                }
            } else if (!this$name.equals(other$name)) {
                return false;
            }

            if (this.getAge() != other.getAge()) {
                return false;
            } else if (Double.compare(this.getScore(), other.getScore()) != 0) {
                return false;
            } else if (!Arrays.deepEquals(this.getTags(), other.getTags())) {
                return false;
            } else {
                return true;
            }
        }
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $name = this.getName();
        int result = result * 59 + ($name == null ? 43 : $name.hashCode());
        result = result * 59 + this.getAge();
        long $score = Double.doubleToLongBits(this.getScore());
        result = result * 59 + (int)($score >>> 32 ^ $score);
        result = result * 59 + Arrays.deepHashCode(this.getTags());
        return result;
    }

    public String toString() {
        return "LomBokValue(name=" + this.getName() + ", age=" + this.getAge() + ", score=" + this.getScore() + ", tags=" + Arrays.deepToString(this.getTags()) + ")";
    }

    public static final class Exercise<T> {
        private final String name;
        private final T value;

        private Exercise(String name, T value) {
            this.name = name;
            this.value = value;
        }

        public static <T> LomBokValue.Exercise<T> of(String name, T value) {
            return new LomBokValue.Exercise(name, value);
        }

        public String getName() {
            return this.name;
        }

        public T getValue() {
            return this.value;
        }

        public boolean equals(Object o) {
            if (o == this) {
                return true;
            } else if (!(o instanceof LomBokValue.Exercise)) {
                return false;
            } else {
                LomBokValue.Exercise<?> other = (LomBokValue.Exercise)o;
                Object this$name = this.getName();
                Object other$name = other.getName();
                if (this$name == null) {
                    if (other$name != null) {
                        return false;
                    }
                } else if (!this$name.equals(other$name)) {
                    return false;
                }

                Object this$value = this.getValue();
                Object other$value = other.getValue();
                if (this$value == null) {
                    if (other$value != null) {
                        return false;
                    }
                } else if (!this$value.equals(other$value)) {
                    return false;
                }

                return true;
            }
        }

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

        public String toString() {
            return "LomBokValue.Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")";
        }
    }
}
View Code

11. @Builder

// 源码:
package com.test.lombok.builder;

import lombok.Builder;
import lombok.Singular;

import java.util.Set;

@Builder
public class LomBokBuilder {
    private String name;
    private int age;
    @Singular
    private Set<String> occupations;
}

// 生成的class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.builder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

public class LomBokBuilder {
    private String name;
    private int age;
    private Set<String> occupations;

    LomBokBuilder(String name, int age, Set<String> occupations) {
        this.name = name;
        this.age = age;
        this.occupations = occupations;
    }

    public static LomBokBuilder.LomBokBuilderBuilder builder() {
        return new LomBokBuilder.LomBokBuilderBuilder();
    }

    public static class LomBokBuilderBuilder {
        private String name;
        private int age;
        private ArrayList<String> occupations;

        LomBokBuilderBuilder() {
        }

        public LomBokBuilder.LomBokBuilderBuilder name(String name) {
            this.name = name;
            return this;
        }

        public LomBokBuilder.LomBokBuilderBuilder age(int age) {
            this.age = age;
            return this;
        }

        public LomBokBuilder.LomBokBuilderBuilder occupation(String occupation) {
            if (this.occupations == null) {
                this.occupations = new ArrayList();
            }

            this.occupations.add(occupation);
            return this;
        }

        public LomBokBuilder.LomBokBuilderBuilder occupations(Collection<? extends String> occupations) {
            if (this.occupations == null) {
                this.occupations = new ArrayList();
            }

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

        public LomBokBuilder.LomBokBuilderBuilder clearOccupations() {
            if (this.occupations != null) {
                this.occupations.clear();
            }

            return this;
        }

        public LomBokBuilder build() {
            Set occupations;
            switch(this.occupations == null ? 0 : this.occupations.size()) {
            case 0:
                occupations = Collections.emptySet();
                break;
            case 1:
                occupations = Collections.singleton(this.occupations.get(0));
                break;
            default:
                Set<String> occupations = new LinkedHashSet(this.occupations.size() < 1073741824 ? 1 + this.occupations.size() + (this.occupations.size() - 3) / 3 : 2147483647);
                occupations.addAll(this.occupations);
                occupations = Collections.unmodifiableSet(occupations);
            }

            return new LomBokBuilder(this.name, this.age, occupations);
        }

        public String toString() {
            return "LomBokBuilder.LomBokBuilderBuilder(name=" + this.name + ", age=" + this.age + ", occupations=" + this.occupations + ")";
        }
    }
}
View Code

12. @SneakyThrows

// 源码:
package com.test.lombok.sneakyThrows;

import lombok.SneakyThrows;

import java.io.UnsupportedEncodingException;

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

    @SneakyThrows
    public void run() {
        throw new Throwable();
    }
}

// 生成的class文件
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.sneakyThrows;

import java.io.UnsupportedEncodingException;

public class LomBokSneakyThrows implements Runnable {
    public LomBokSneakyThrows() {
    }

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

    public void run() {
        try {
            throw new Throwable();
        } catch (Throwable var2) {
            throw var2;
        }
    }
}
View Code

13. @Synchronized

// 源码:
package com.test.lombok.synchronize;

import lombok.Synchronized;

/**
 * @Synchronized 是synchronized method修饰符的另一种形式. 可以用在静态方法或者实例方法上
 * 作用与synchronize类似,synchronize锁定当前对象this,注解锁定不同的对象
 */
public class LomBokSynchronize {
    private final Object readLock = new Object();

    @Synchronized
    public static void hello() {
        System.out.println("world");
    }

    @Synchronized
    public int answerToLife() {
        return 42;
    }

    @Synchronized("readLock")
    public void foo() {
        System.out.println("bar");
    }
}

// 生成的class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.synchronize;

public class LomBokSynchronize {
    private static final Object $LOCK = new Object[0];
    private final Object $lock = new Object[0];
    private final Object readLock = new Object();

    public LomBokSynchronize() {
    }

    public static void hello() {
        Object var0 = $LOCK;
        synchronized($LOCK) {
            System.out.println("world");
        }
    }

    public int answerToLife() {
        Object var1 = this.$lock;
        synchronized(this.$lock) {
            return 42;
        }
    }

    public void foo() {
        Object var1 = this.readLock;
        synchronized(this.readLock) {
            System.out.println("bar");
        }
    }
}
View Code

14. @Getter(lazy=true)

// 源码:
package com.test.lombok.getterLazy;

import lombok.Getter;

public class LomBokGetterLazy {
    @Getter(lazy=true) private final double[] cached = expensive();

    private double[] expensive() {
        double[] result = new double[1000000];
        for (int i = 0; i < result.length; i++) {
            result[i] = Math.asin(i);
        }
        return result;
    }
}

// 生成的class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.getterLazy;

import java.util.concurrent.atomic.AtomicReference;

public class LomBokGetterLazy {
    private final AtomicReference<Object> cached = new AtomicReference();

    public LomBokGetterLazy() {
    }

    private double[] expensive() {
        double[] result = new double[1000000];

        for(int i = 0; i < result.length; ++i) {
            result[i] = Math.asin((double)i);
        }

        return result;
    }

    public double[] getCached() {
        Object value = this.cached.get();
        if (value == null) {
            AtomicReference var2 = this.cached;
            synchronized(this.cached) {
                value = this.cached.get();
                if (value == null) {
                    double[] actualValue = this.expensive();
                    value = actualValue == null ? this.cached : actualValue;
                    this.cached.set(value);
                }
            }
        }

        return (double[])((double[])(value == this.cached ? null : value));
    }
}
View Code

15. @Log

// 源码:
package com.test.lombok.log;

import lombok.extern.java.Log;

@Log
public class LomBokLog {
    public static void main(String... args) {
        log.info("Something's wrong here");
    }
}

// 生成的class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.log;

import java.util.logging.Logger;

public class LomBokLog {
    private static final Logger log = Logger.getLogger(LomBokLog.class.getName());

    public LomBokLog() {
    }

    public static void main(String... args) {
        log.info("Something's wrong here");
    }
}
View Code

16. experiment

(1) @Accessor

// 源码:
package com.test.lombok.accessor;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

@Accessors(fluent = true)
public class LomBokAccessor {
    @Getter
    @Setter
    private int age = 10;
}

class PrefixExample {
    @Accessors(prefix = "f")
    @Getter
    @Setter
    private String fName = "Hello, World!";
}


// 生成的class文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.accessor;

public class LomBokAccessor {
    private int age = 10;

    public LomBokAccessor() {
    }

    public int age() {
        return this.age;
    }

    public LomBokAccessor age(int age) {
        this.age = age;
        return this;
    }
}

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.test.lombok.accessor;

class PrefixExample {
    private String fName = "Hello, World!";

    PrefixExample() {
    }

    public String getName() {
        return this.fName;
    }

    public void setName(String fName) {
        this.fName = fName;
    }
}
View Code

posted on 2018-03-10 15:44  maoshiling  阅读(1681)  评论(0编辑  收藏  举报

导航