技术笔记: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);


相关文章
|
1月前
|
Java 测试技术 微服务
最新技术栈下 Java 面试高频技术点实操指南详解
本指南结合最新Java技术趋势,涵盖微服务(Spring Cloud Alibaba)、响应式编程(Spring WebFlux)、容器化部署(Docker+Kubernetes)、函数式编程、性能优化及测试等核心领域。通过具体实现步骤与示例代码,深入讲解服务注册发现、配置中心、熔断限流、响应式数据库访问、JVM调优等内容。适合备战Java面试,提升实操能力,助力技术进阶。资源链接:[https://pan.quark.cn/s/14fcf913bae6](https://pan.quark.cn/s/14fcf913bae6)
99 25
|
29天前
|
监控 Java 测试技术
2025 年 Java 核心技术从入门到精通实战指南
《2025年Java核心技术实战指南》全面覆盖Java开发的最新趋势与最佳实践。内容包括Java新特性(如模式匹配、文本块、记录类)、微服务架构(Spring Boot 3.0+、Spring Cloud)、响应式编程(Reactor、WebFlux)、容器化与云原生(Docker、Kubernetes)、数据访问技术(JPA、R2DBC)、函数式编程、单元测试与集成测试(JUnit 5、Mockito)、性能优化与监控等。通过实战案例,帮助开发者掌握构建高性能、高可用系统的技能。代码资源可从[链接](https://pan.quark.cn/s/14fcf913bae6)获取。
120 7
|
29天前
|
IDE Java 开发工具
Java 基础篇必背综合知识点最新技术与实操应用全面总结指南
本总结梳理了Java 17+的核心知识点与新技术,涵盖基础概念(模块化系统、GraalVM)、数据类型(文本块、模式匹配)、流程控制(增强switch)、面向对象(Record类、密封类)、常用类库(Stream API、HttpClient)、实战案例(文件处理)、构建工具(Maven、Gradle)、测试框架(JUnit 5)、开发工具(IDE、Git)及云原生开发(Spring Boot 3、Docker)。通过理论结合实操,帮助开发者掌握Java最新特性并应用于项目中。代码示例丰富,建议配合实践加深理解。
65 4
|
22天前
|
安全 Java API
Java 17 + 特性与现代开发技术实操应用详解
本指南聚焦Java 17+最新技术,涵盖模块化开发、Record类、模式匹配、文本块、Stream API增强、虚拟线程等核心特性,结合Spring Boot 3与Micronaut框架实战。通过实操案例解析现代Java开发技术栈,包括高性能并发编程、GraalVM原生编译及开发工具链配置。同时梳理面试高频考点,助力掌握Java新特性和实际应用,适合学习与项目实践。代码示例丰富,附带完整资源下载链接。
249 0
|
20天前
|
消息中间件 机器学习/深度学习 Java
java 最新技术驱动的智能教育在线实验室设备管理与实验资源优化实操指南
这是一份基于最新技术的智能教育在线实验室设备管理与实验资源优化的实操指南,涵盖系统搭建、核心功能实现及优化策略。采用Flink实时处理、Kafka消息队列、Elasticsearch搜索分析和Redis缓存等技术栈,结合强化学习动态优化资源调度。指南详细描述了开发环境准备、基础组件部署、数据采集与处理、模型训练、API服务集成及性能调优步骤,支持高并发设备接入与低延迟处理,满足教育机构数字化转型需求。代码已提供下载链接,助力快速构建智能化实验室管理系统。
86 44
|
1月前
|
Java API 微服务
2025 年 Java 核心技术全面升级与实战应用详解
这份Java校招实操内容结合了最新技术趋势,涵盖核心技术、微服务架构、响应式编程、DevOps及前沿技术等六大模块。从函数式编程到Spring Cloud微服务,再到容器化与Kubernetes部署,帮助你掌握企业级开发技能。同时,提供AI集成、区块链实践和面试技巧,包括高频算法题与系统设计案例。通过学习这些内容,可应对90%以上的Java校招技术面试,并快速上手实际项目开发。资源链接:[点此获取](https://pan.quark.cn/s/14fcf913bae6)。
211 41
|
22天前
|
SQL Kubernetes Java
Java 最新技术实操:从基础到进阶的详细指南
本文介绍了Java 17及后续版本的核心技术实操,涵盖新特性、集合框架、异常处理和多线程编程等内容。主要包括:密封类(Sealed Classes)的继承层级控制、模式匹配(Pattern Matching)简化类型判断、文本块(Text Blocks)处理多行字符串;集合框架中的工厂方法和Stream API高级操作;异常处理的最佳实践如自动资源管理(ARM)和自定义异常;多线程编程中的CompletableFuture异步编程和ReentrantLock显式锁使用。
81 6
|
24天前
|
安全 Java API
Java最新技术(JDK 11+) 及以上 Java 最新技术之集合框架实操应用详解
本示例基于Java最新技术(JDK 11+),涵盖集合框架的核心功能,结合Java 8+特性(如Stream API、Lambda表达式)与并发编程最佳实践。内容包括:List操作(初始化、Lambda过滤、Stream处理)、Map操作(流式过滤、ConcurrentHashMap原子操作、并行流)、Set操作(TreeSet排序、CopyOnWriteArraySet并发安全)、Queue/Deque操作(优先队列、双端队列)以及高级聚合操作(集合转换、分组统计、平均值计算)。 [代码下载](https://pan.quark.cn/s/14fcf913bae6)
39 4
|
28天前
|
Java
Java 编译与解释并存使用方法的详细解析
本文介绍了Java编译与解释并存的使用方法及其组件封装技巧。首先讲解了如何通过`javac`编译源代码生成字节码,再由JVM解释执行,并利用JIT编译优化性能。接着详细说明了基于接口的组件设计、实现、注册和动态加载方法,以及通过JAR文件进行模块化封装和依赖注入支持。最后提供了一个完整的组件化应用示例,展示如何根据输入动态选择处理器。这种机制充分发挥了Java的跨平台特性与运行时性能优化能力,适合用于构建灵活、可扩展的应用系统。
28 1

热门文章

最新文章