Lombok

本文内容参考自:http://blog.csdn.net/hack8/article/details/23790579 和  http://www.cnblogs.com/holten/p/5729226.html

1.简介:

官网地址:https://projectlombok.org/ 首页有一段几分钟的演示视频,看完就明白是怎么回事了。

Lombok注解在线帮助文档地址:https://projectlombok.org/features/all

lombok的Github地址:https://github.com/rzwitserloot/lombok

Lombok是一个基于LGPL的开源J2EE综合开发环境的Eclipse插件,对编码,发布,测试,以及debug等各个软件开发的生命周期提供支持,支持JSP,EJB等。Lomboz是Eclipse的一个J2EE的插件,它将很多Java应用服务器、J2EE组件和Web应用开发集成到Eclipse中,可以帮助Java开发者使用Eclipse建立、测试、部署J2EE应用。

  lombok 以简单的注解的形式来精简 java 代码,提升开发人员生产效率的辅助工具。特别是相对于 POJO,利用注解在编译期自动生成setter/getter/toString()/constructor之类的代码。

2.lombok 安装:

 使用 lombok 是需要安装的,如果不安装,IDE 则无法解析 lombok 注解。先在官网下载最新版本的 JAR 包,我下载的是lombok-1.16.4.jar

(1). 法一:双击下载下来的 JAR 包安装 lombok
    安装目录为eclipse安装路径,安装完成后,查看eclipse.ini 是否出现配置:

  -Xbootclasspath/a:lombok.jar
        -javaagent:lombok.jar                          若出现,则说明安装成功。
(2).法二:eclipse / myeclipse 手动安装 lombok
    a. 将 lombok.jar 复制到 myeclipse.ini / eclipse.ini 所在的文件夹目录下
    b. 打开 eclipse.ini / myeclipse.ini,在最后面插入以下两行并保存:
        -Xbootclasspath/a:lombok.jar
        -javaagent:lombok.jar
    c.重启 eclipse / myeclipse

(3)法三:

3.Maven添加依赖

<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.10</version>
    </dependency>
</dependencies>

4.lombok 注解:
    lombok 提供的注解不多,可以参考官方视频的讲解和官方文档。
    Lombok 注解在线帮助文档:http://projectlombok.org/features/index.
    下面介绍几个我常用的 lombok 注解:
 (1)@Data   :注解在类上;
自动为所有字段添加@ToString, @EqualsAndHashCode, @Getter方法,为非final字段添加@Setter,和@RequiredArgsConstructor!

 (2)@Setter/@Gette:注解在属性上;为属性提供 setting/getting 方法(自动生成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;
    }
}


 (3)@Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象

 (4)@Slf4j :    注解在类上;为类提供一个 属性名为log 的 log4j 日志对象
 (5)@NoArgsConstructor:注解在类上;为类提供一个无参的构造方法
 (6)@AllArgsConstructor:注解在类上;为类提供一个全参的构造方法

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

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

 5.简单示例:

(作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。)

(1)使用 lombok 的方案

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
import java.io.*;
import java.util.ArrayList;
 
@Data
@Slf4j
@AllArgsConstructor
public class Something {
 
    private String name;
    private final String country;
    private final Object lockObj = new Object();
 
    public void sayHello(@NonNull String target) {
        String content = String.format("hello,%s", target);
        System.out.println(content);
        log.info(content);
    }
 
    public void addBalabala() {
        val list = new ArrayList<String>();
        list.add("haha");
        System.out.println(list.size());
    }
 
    @SneakyThrows(IOException.class)
    public void closeBalabala() {
        @Cleanup InputStream is = new ByteArrayInputStream("hello world".getBytes());
        System.out.println(is.available());
    }
 
    @Synchronized("lockObj")
    public void lockMethod() {
        System.out.println("test lock method");
    }
}

(2)不使用 lombok 的方案

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import java.beans.ConstructorProperties;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class Something {
    private static final Logger log = LoggerFactory.getLogger(Something.class);
    private String name;
    private final String country;
    private final Object lockObj = new Object();
 
    public void sayHello(@NonNull String target) {
        if(target == null) {
            throw new NullPointerException("target");
        } else {
            String content = String.format("hello,%s", new Object[]{target});
            System.out.println(content);
            log.info(content);
        }
    }
 
    public void addBalabala() {
        ArrayList list = new ArrayList();
        list.add("haha");
        System.out.println(list.size());
    }
 
    public void closeBalabala() {
        try {
            ByteArrayInputStream $ex = new ByteArrayInputStream("hello world".getBytes());
 
            try {
                System.out.println($ex.available());
            } finally {
                if(Collections.singletonList($ex).get(0) != null) {
                    $ex.close();
                }
 
            }
 
        } catch (IOException var6) {
            throw var6;
        }
    }
 
    public void lockMethod() {
        Object var1 = this.lockObj;
        synchronized(this.lockObj) {
            System.out.println("test lock method");
        }
    }
 
    public String getName() {
        return this.name;
    }
 
    public String getCountry() {
        return this.country;
    }
 
    public Object getLockObj() {
        return this.lockObj;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public boolean equals(Object o) {
        if(o == this) {
            return true;
        } else if(!(o instanceof Something)) {
            return false;
        } else {
            Something other = (Something)o;
            if(!other.canEqual(this)) {
                return false;
            } else {
                label47: {
                    String this$name = this.getName();
                    String other$name = other.getName();
                    if(this$name == null) {
                        if(other$name == null) {
                            break label47;
                        }
                    } else if(this$name.equals(other$name)) {
                        break label47;
                    }
 
                    return false;
                }
 
                String this$country = this.getCountry();
                String other$country = other.getCountry();
                if(this$country == null) {
                    if(other$country != null) {
                        return false;
                    }
                } else if(!this$country.equals(other$country)) {
                    return false;
                }
 
                Object this$lockObj = this.getLockObj();
                Object other$lockObj = other.getLockObj();
                if(this$lockObj == null) {
                    if(other$lockObj != null) {
                        return false;
                    }
                } else if(!this$lockObj.equals(other$lockObj)) {
                    return false;
                }
 
                return true;
            }
        }
    }
 
    protected boolean canEqual(Object other) {
        return other instanceof Something;
    }
 
    public int hashCode() {
        boolean PRIME = true;
        byte result = 1;
        String $name = this.getName();
        int result1 = result * 59 + ($name == null?0:$name.hashCode());
        String $country = this.getCountry();
        result1 = result1 * 59 + ($country == null?0:$country.hashCode());
        Object $lockObj = this.getLockObj();
        result1 = result1 * 59 + ($lockObj == null?0:$lockObj.hashCode());
        return result1;
    }
 
    public String toString() {
        return "Something(name=" + this.getName() + ", country=" + this.getCountry() + ", lockObj=" + this.getLockObj() + ")";
    }
 
    @ConstructorProperties({"name", "country"})
    public Something(String name, String country) {
        this.name = name;
        this.country = country;
    }
}

上面的两个 java 类,从作用上来看,它们的效果是一样的,相比较之下,很明显,使用 lombok 要简洁许多,特别是在类的属性较多的情况下,
同时也避免了修改字段名字时候忘记修改方法名所犯的低级错误。

最后需要注意的是,在使用 lombok 注解的时候记得要导入 lombok.jar 包到工程 

原文地址:https://www.cnblogs.com/whhjava/p/7049731.html