技术笔记:Lombok介绍、使用方法和总结

简介: 技术笔记:Lombok介绍、使用方法和总结

同步首发:


1 Lombok背景介绍


官方介绍如下:


Project Lombok makes java a spicier language by adding 'handlers' that know how to build and compile simple, boilerplate-free, not-quite-java code.


大致意思是Lombok通过增加一些“处理程序”,可以让java变得简洁、快速。


2 Lombok使用方法


Lombok能以简单的注解形式来简化java代码,提高开发人员的开发效率。例如开发中经常需要写的javabean,都需要花时间去添加相应的getter/setter,也许还要去写构造器、equals等方法,而且需要维护,当属性多时会出现大量的getter/setter方法,这些显得很冗长也没有太多技术含量,一旦修改属性,就容易出现忘记修改对应方法的失误。


Lombok能通过注解的方式,在编译时自动为属性生成构造器、getter/setter、equals、hashcode、toString方法。出现的神奇就是在源码中没有getter和setter方法,但是在编译生成的字节码文件中有getter和setter方法。这样就省去了手动重建这些代码的麻烦,使代码看起来更简洁些。


Lombok的使用跟引用jar包一样,可以在官网(下载jar包,也可以使用maven添加依赖:


[/span>dependency

[/span>groupId

[/span>artifactId

[/span>version

[/span>scope


接下来我们来分析Lombok中注解的具体用法。


2.1 @Data


@Data注解在类上,会为类的所有属性自动生成setter/getter、equals、canEqual、hashCode、toString方法,如为final属性,则不会为该属性生成setter方法。


官方实例如下:


import lombok.AccessLevel;


import lombok.Setter;


import lombok.Data;


import lombok.ToString;


@Data public class DataExample {


private final String name;


@Setter(AccessLevel.PACKAGE) private int age;


private double score;


private String【】 tags;


@ToString(includeFieldNames=true)


@Data(staticConstructor="of")


public static class Exercise {


private final String name;


private final T value;


}


}


如不使用Lombok,则实现如下:


import java.util.Arrays;


public class DataExample {


private final String name;


private int age;


private double score;


private String【】 tags;


public DataExample(String name) {


this.name = name;


}


public String getName() {


return this.name;


}


void setAge(int age) {


this.age = age;


}


public int getAge() {


return this.age;


}


public void setScore(double score) {


this.score = score;


}


public double getScore() {


return this.score;


}


public String【】 getTags() {


return this.tags;


}


public void setTags(String【】 tags) {


this.tags = tags;


}


@Override public String toString() {


return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")";


}


protected boolean canEqual(Object other) {


return other instanceof DataExample;


}


@Override public boolean equals(Object o) {


if (o == this) return true;


if (!(o instanceof DataExample)) return false;


DataExample other = (DataExample) o;


if (!other.canEqual((Object)this)) return false;


if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;


if (this.getAge() != other.getAge()) return false;


if (Double.compare(this.getScore(), other.getScore()) != 0) return false;


if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;


return true;


}


@Override public int hashCode() {


final int PRIME = 59;


int result = 1;


final long temp1 = Double.doubleToLongBits(this.getScore());


result = (resultPRIME) + (this.getName() == null ? 43 : this.getName().hashCode());


result = (resultPRIME) + this.getAge();


result = (resultPRIME) + (int)(temp1 ^ (temp1 ]> 32));


result = (resultPRIME) + Arrays.deepHashCode(this.getTags());


return result;


}


public static class Exercise {


private final String name;


private final T value;


private Exercise(String name, T value) {


this.name = name;


this.value = value;


}


public static Exercise of(String name, T value) {


return new Exercise(name, value);


}


public String getName() {


return this.name;


}


public T getValue() {


return this.value;


}


@Override public String toString() {


return "Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")";


}


protected boolean canEqual(Object other) {


return other instanceof Exercise;


}


@Override public boolean equals(Object o) {


if (o == this) return true;


if (!(o instanceof Exercise)) return false;


Exercise other = (Exercise) o;


if (!other.canEqual((Object)this)) return false;


if (this.getName() == null ? other.getValue() != null : !this.getName().equals(other.getName())) return false;


if (this.getValue() == null ? other.getValue() != null : !this.getValue().equals(other.getValue())) return false;


return true;


}


@Override public int hashCode() {


final int PRIME = 59;


int result = 1;


result = (resultPRIME) + (this.getName() == null ? 43 : this.getName().hashCode());


result = (resultPRIME) + (this.getValue() == null ? 43 : this.getValue().hashCode());


return result;


}


}


}


2.2 @Getter/@Setter


如果觉得@Data太过残暴(因为@Data集合了@ToString、@EqualsAndHashCode、@Getter/@Setter、@RequiredArgsConstructor的所有特性)不够精细,可以使用@Getter/@Setter注解,此注解在属性上,可以为相应的属性自动生成Getter/Setter方法,示例如下:


import lombok.AccessLevel;


import lombok.Getter;


import lombok.Setter;


public class GetterSetterExample {


@Getter @Setter private int age = 10;


@Setter(AccessLevel.PROTECTED) private String name;


@Override public String toString() {


return String.format("%s (age: %d)", name, age);


}


}


如果不使用Lombok:


public class GetterSetterExample {


private int age = 10;


private String name;


@Override public String toString() {


return String.format("%s (age: %d)", name, age);


}


public int getAge() {


return age;


}


public void setAge(int age) {


this.age = age;


}


protected void setName(String name) {


this.name = name;


}


}


2.3 @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:


import lombok.NonNull;


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


}


}


2.4 @Cleanup


该注解能帮助我们自动调用close()方法,很大的简化了代码。


示例如下:


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 //代码效果参考:http://www.jhylw.com.cn/303634411.html

(true) {

int r = in.read(b);


相关文章
|
2天前
|
安全 Java Apache
Java中的数据安全与隐私保护技术
Java中的数据安全与隐私保护技术
|
2天前
|
存储 缓存 NoSQL
Java中的内存数据库与缓存技术
Java中的内存数据库与缓存技术
|
2天前
|
存储 算法 安全
实现Java应用的数据加密与解密技术
实现Java应用的数据加密与解密技术
|
2天前
|
存储 安全 算法
Java中的数据加密与数字签名技术
Java中的数据加密与数字签名技术
|
3天前
|
Java UED 程序员
解决Java中的IllegalArgumentException异常的技术实践
解决Java中的IllegalArgumentException异常的技术实践
|
3天前
|
网络协议 Java
Java网络编程基础与Socket实现技术
Java网络编程基础与Socket实现技术
|
3天前
|
安全 Java 测试技术
Java中的反射与元编程技术探秘
Java中的反射与元编程技术探秘
|
3天前
|
Java 调度 开发者
Java定时器的使用方法与调度策略
Java定时器的使用方法与调度策略
|
3天前
|
并行计算 Java 大数据
Java中的高效并行计算与多线程编程技术
Java中的高效并行计算与多线程编程技术
|
3天前
|
Java 网络协议
解决Java中的ProtocolException异常的技术实践
解决Java中的ProtocolException异常的技术实践