lombok的注解分别是什么作用?

Maven添加lombok


    
        org.projectlombok
        lombok
        1.16.10
    

注解及其作用:
@NoArgsConstructor: 自动生成无参数构造函数。
@AllArgsConstructor: 自动生成全参数构造函数。
@Data: 自动为所有字段添加@ToString, @EqualsAndHashCode, @Getter方法,为非final字段添加@Setter,和@RequiredArgsConstructor!

@NonNull: 可以帮助我们避免空指针。
使用lombok:

import lombok.NonNull;
    public class NonNullExample extends Something {
        private String name;  
        public NonNullExample(@NonNull Person person) {
        super("Hello");
        this.name = person.getName();
    }
}

不使用lombok:

public class NonNullExample extends Something {
    private String name;  
    public NonNullExample(@NonNull Person person) {
        super("Hello");
        if (person == null) {
            throw new NullPointerException("person");
        }
        this.name = person.getName();
    }
}

@Cleanup: 自动帮我们调用close()方法。
使用lombok:

import lombok.Cleanup;
import java.io.*;
public class CleanupExample {
    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);
        }
    }
}

不使用lombok:

import java.io.*;
    public class CleanupExample {
        public static void main(String[] args) throws IOException {
            InputStream in = new FileInputStream(args[0]);
            try {
                OutputStream out = new FileOutputStream(args[1]);
                try {
                    byte[] b = new byte[10000];
                    while (true) {
                    int r = in.read(b);
                    if (r == -1) break;
                    out.write(b, 0, r);
                    }
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
            } finally {
                if (in != null) {
                in.close();
            }
        }
    }
}

@Getter / @Setter: 自动生成Getter/Setter方法
使用lombok:

    import lombok.AccessLevel;
    import lombok.Getter;
    import lombok.Setter;
    public class GetterSetterExample {
        @Getter @Setter private int age = 10;
        @Setter(AccessLevel.PROTECTED) private String name;
    }

不使用lombok:

public class GetterSetterExample {
    private int age = 10;
    private String name;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    protected void setName(String name) {
        this.name = name;
    }
}

你可能感兴趣的:(工具类,lombok,lombok作用,lombok注解)