使用 Lombok 简化项目中无谓的Java代码
在写使用Java时,难免会有一些模板代码要写,不然get/set,toString, hashCode, close 资源,定义构造函数等等。代码会显得很冗余,很长。Lombok项目可以是我们摆脱这些东西,通过一系列的注解,Lombok可以帮我们自动生成这些函数。Lombok 官网地址:https://projectlombok.org/
参考文档:https://projectlombok.org/features/index.html
1. 安装
到官网下载 lombok.jar,直接双击,按照提示进行操作,就可以在eclipse中安装成功。
如果使用maven时,则需要引入依赖:<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.4</version>
<scope>provided</scope>
</dependency>如果需要用javac或者其他命令工具编译java类,则需要将 lombok.jar放入classpath.
2. 使用方法 (文档:https://projectlombok.org/features/index.html)
1> @Getter/@Setter, 注解在一个pojo类上,会在编译时,帮我们自动生成get/set函数。
2> @ToString 注解在类上,编译时,帮我们生成包括所有field的toString函数;
3> @EqualsAndHashCode,编译时,帮我们生成equlas 和hashCode函数;
4> @Cleanup, 注解在一些资源对象的定义上,可以帮我们自动调用它们的close()函数;这个很有帮助;
5> @NoArgsContructor,@RequireArgsContructor, @AllArgsContructor,分别帮我们生成无参数构造函数,每一个非Null的field的构造函数,所有field参数的构造函数;
6> @Data,All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor! (等价于:@ToString, @EqualsAndHashCode, @Getter, @Setter, @RequiredArgsConstructor)
更多的注解,参见https://projectlombok.org/features/index.html
3. 例子@Data
@AllArgsConstructor
@NoArgsConstructor
public class Test {
private int id;
private String name;
private String password;
public static void main(String[] args) {
Test test = new Test(1, "test", "password");
System.out.println(test);
System.out.println(test.getName());
}
}结果:Test(id=1, name=test, password=password)
test通过@Data, @AllArgsConstructor,@NoArgsConstructor 三个注解自动 生成了 Test 的全field参数的构造函数,自动生成了 toString(), get/set函数等等。
再看一例:public static void main(String[] args) throws IOException{
@Cleanup
InputStream in = new FileInputStream("/home/a.txt");
@Cleanup
OutputStream out = new FileOutputStream("/home/b.txt");
byte[] b = new byte;
while (true) {
int r = in.read(b);
if (r == -1)
break;
out.write(b, 0, r);
}
}@Cleanup自动帮我们调用 close() 方法进行关闭资源。
You can use @Cleanup to ensure a given resource is automatically cleaned up before the code execution path exits your current scope. You do this by annotating any local variable declaration with the @Cleanup annotation like so:
@Cleanup InputStream in = new FileInputStream("some/file");
As a result, at the end of the scope you're in, in.close() is called. This call is guaranteed to run by way of a try/finally construct.
If the type of object you'd like to cleanup does not have a close() method, but some other no-argument method, you can specify the name of this method like so:
@Cleanup("dispose") org.eclipse.swt.widgets.CoolBar bar = new CoolBar(parent, 0);
By default, the cleanup method is presumed to be close(). A cleanup method that takes 1 or more arguments cannot be called via @Cleanup.
@Cleanup是通过 try/finally 实现的,如果资源的关闭方法不是默认的close(),那么也可以指定关闭方法的名称@Cleanup("closeMethod"), 但是关闭方法不能有参数,不然就无法使用 @Cleanup了。
更多的 参考 https://projectlombok.org/features/index.html
通过使用 Lombok,可以减少很多的 Java 代码的,减轻了心理负担。
页:
[1]