1. val

自动识别循环变量类型

本地变量和foreach循环可用。

import java.util.ArrayList;
import java.util.HashMap;
import lombok.val; public class ValExample {
public String example() {
val example = new ArrayList<String>();
example.add("Hello, World!");
val foo = example.get(0);
return foo.toLowerCase();
} public void example2() {
val map = new HashMap<Integer, String>();
map.put(0, "zero");
map.put(5, "five");
//直接使用val即可遍历
for (val entry : map.entrySet()) {
System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
}
}
}

2. @NonNull

自动检查该变量是否为null,若为null则抛出NullPointerException异常

import lombok.NonNull;

public class NonNullExample extends Something {
private String name; public NonNullExample(@NonNull Person person) {
super("Hello");
this.name = person.getName();
}
} 等同于 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 is marked non-null but is null");
}
this.name = person.getName();
}
}

3. @Cleanup

使用@Clean可以自动关闭流资源

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);
}
}
} 等同于 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();
}
}
}
}

4. @Getter and @Setter

自动生成对应的 getter 方法和 setter 方法

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter; public class GetterSetterExample {
/**
* Age of the person. Water is wet.
*
* @param age New value for this person's age. Sky is blue.
* @return The current value of this person's age. Circles are round.
*/
@Getter @Setter private int age = 10; /**
* Name of the person.
* -- SETTER --
* Changes the name of this person.
*
* @param name The new value.
*/
@Setter(AccessLevel.PROTECTED) private String name; @Override public String toString() {
return String.format("%s (age: %d)", name, age);
}
}

@Getter(lazy=true)

该注释可以缓存第一次访问getter方法的值,后续使用getter都是第一次访问getter的值

5. @ToString

自动生成 toString 方法

import lombok.ToString;

@ToString
public class ToStringExample {
private static final int STATIC_VAR = 10;
private String name;
private Shape shape = new Square(5, 10);
private String[] tags;
@ToString.Exclude private int id; public String getName() {
return this.name;
} @ToString(callSuper=true, includeFieldNames=true)
public static class Square extends Shape {
private final int width, height; public Square(int width, int height) {
this.width = width;
this.height = height;
}
}
}

6. @EqualsAndHashCode

自动生成 equals 方法和 hashCode 方法

import lombok.EqualsAndHashCode;

@EqualsAndHashCode
public class EqualsAndHashCodeExample {
private transient int transientVar = 10;
private String name;
private double score;
@EqualsAndHashCode.Exclude private Shape shape = new Square(5, 10);
private String[] tags;
@EqualsAndHashCode.Exclude private int id; public String getName() {
return this.name;
} @EqualsAndHashCode(callSuper=true)
public static class Square extends Shape {
private final int width, height; public Square(int width, int height) {
this.width = width;
this.height = height;
}
}
}

7. @NoArgsConstructor and @AllArgsConstructor

自动生成无参构造器和全参构造器

可选参数access

access = AccessLevel.PROTECTED等

import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor; @NoArgsConstructor
@AllArgsConstructor
public class ConstructorExample { private Integer id; private String name;
}

8. @RequiredArgsConstructor

Lombok提供的自动注入,注入的对象的字段全部需要是 final 的。

可能会造成循环依赖,慎用。

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor(staticName = "pocket")
public class ConstructorExample { private Integer id; private String name;
}

9. @Data

复合注解,包含以下注解:@ToString,@EqualsAndHashCode,@Getter,@Setter,@RequiredArgsConstructor

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<T> {
private final String name;
private final T value;
}
}

10. @Value

作用于类,使所有的成员变量都是 final 的

import lombok.AccessLevel;
import lombok.experimental.NonFinal;
import lombok.experimental.Value;
import lombok.experimental.With;
import lombok.ToString; @Value public class ValueExample {
String name;
@With(AccessLevel.PACKAGE) @NonFinal int age;
double score;
protected String[] tags; @ToString(includeFieldNames=true)
@Value(staticConstructor="of")
public static class Exercise<T> {
String name;
T value;
}
}

11. @Builder

作用于类,使之可以链式注入属性

Person.builder()
.name("Adam Savage")
.city("San Francisco")
.job("Mythbusters")
.job("Unchained Reaction")
.build();

12. @SneakyThrows

减少异常处理,直接抛出异常即可,无需处理

import lombok.SneakyThrows;

public class SneakyThrowsExample implements Runnable {
@SneakyThrows(UnsupportedEncodingException.class)
public String utf8ToString(byte[] bytes) {
return new String(bytes, "UTF-8");
} @SneakyThrows
public void run() {
throw new Throwable();
}
} 等同于 import lombok.Lombok; public class SneakyThrowsExample implements Runnable {
public String utf8ToString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw Lombok.sneakyThrow(e);
}
} public void run() {
try {
throw new Throwable();
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
}

13. @Synchronized

只能作用于方法,为方法操作添加代码块

import lombok.Synchronized;

public class SynchronizedExample {
private final Object readLock = new Object(); @Synchronized
public static void hello() {
System.out.println("world");
} @Synchronized
public int answerToLife() {
return 42;
} @Synchronized("readLock")
public void foo() {
System.out.println("bar");
}
} 等同于 public class SynchronizedExample {
private static final Object $LOCK = new Object[0];
private final Object $lock = new Object[0];
private final Object readLock = new Object(); public static void hello() {
synchronized($LOCK) {
System.out.println("world");
}
} public int answerToLife() {
synchronized($lock) {
return 42;
}
} public void foo() {
synchronized(readLock) {
System.out.println("bar");
}
}
}

14. @With

可以作用于类和成员变量,返回复制后的对象

import lombok.AccessLevel;
import lombok.NonNull;
import lombok.With; public class WithExample {
@With(AccessLevel.PROTECTED) @NonNull private final String name;
@With private final int age; public WithExample(@NonNull String name, int age) {
this.name = name;
this.age = age;
}
} 等同于 import lombok.NonNull; public class WithExample {
private @NonNull final String name;
private final int age; public WithExample(String name, int age) {
if (name == null) throw new NullPointerException();
this.name = name;
this.age = age;
} protected WithExample withName(@NonNull String name) {
if (name == null) throw new java.lang.NullPointerException("name");
return this.name == name ? this : new WithExample(name, age);
} public WithExample withAge(int age) {
return this.age == age ? this : new WithExample(name, age);
}
}

15. @Log

使用后可直接使用对应的 log 方法

@CommonsLog
@Flogger
@JBossLog
@Log
@Log4j
@Log4j2
@Slf4j
@XSlf4j
@CustomLog
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j; @Log
public class LogExample { public static void main(String... args) {
log.severe("Something's wrong here");
}
} @Slf4j
public class LogExampleOther { public static void main(String... args) {
log.error("Something else is wrong here");
}
} @CommonsLog(topic="CounterLog")
public class LogExampleCategory { public static void main(String... args) {
log.error("Calling the 'CounterLog' with a message");
}
} 等同于 public class LogExample {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName()); public static void main(String... args) {
log.severe("Something's wrong here");
}
} public class LogExampleOther {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class); public static void main(String... args) {
log.error("Something else is wrong here");
}
} public class LogExampleCategory {
private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog"); public static void main(String... args) {
log.error("Calling the 'CounterLog' with a message");
}
}

Lombok - 快速入门的更多相关文章

  1. Lombok快速入门

    Lombok是简化开发的jar包 借用老师的图来说明

  2. Spring Boot 快速入门笔记

    Spirng boot笔记 简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发 ...

  3. MyBatisPlus快速入门

    MyBatisPlus快速入门 官方网站 https://mp.baomidou.com/guide 慕课网视频 https://www.imooc.com/learn/1130 入门 https:/ ...

  4. springboot2.0整合freemarker快速入门

    目录 1. 快速入门 1.1 创建工程pom.xml文件如下 1.2 编辑application.yml 1.3 创建模型类 1.4 创建模板 1.5 创建controller 1.6 测试 2. F ...

  5. Elastic-Job快速入门

    1 Elastic-Job快速入门1.1 环境搭建1.1.1.版本要求JDK要求1.7及以上版本Maven要求3.0.4及以上版本zookeeper要求采用3.4.6及以上版本1.1.2.Zookee ...

  6. SpringBoot_MyBatisPlus快速入门小例子

    快速入门 创建一个表 我这里随便创建了一个air空气表 idea连接Mysql数据库 点击右侧database再点击添加数据库 找到Mysql 添加用户名,密码,数据库最后点击测试 测试成功后在右侧就 ...

  7. Web Api 入门实战 (快速入门+工具使用+不依赖IIS)

    平台之大势何人能挡? 带着你的Net飞奔吧!:http://www.cnblogs.com/dunitian/p/4822808.html 屁话我也就不多说了,什么简介的也省了,直接简单概括+demo ...

  8. SignalR快速入门 ~ 仿QQ即时聊天,消息推送,单聊,群聊,多群公聊(基础=》提升)

     SignalR快速入门 ~ 仿QQ即时聊天,消息推送,单聊,群聊,多群公聊(基础=>提升,5个Demo贯彻全篇,感兴趣的玩才是真的学) 官方demo:http://www.asp.net/si ...

  9. 前端开发小白必学技能—非关系数据库又像关系数据库的MongoDB快速入门命令(2)

    今天给大家道个歉,没有及时更新MongoDB快速入门的下篇,最近有点小忙,在此向博友们致歉.下面我将简单地说一下mongdb的一些基本命令以及我们日常开发过程中的一些问题.mongodb可以为我们提供 ...

随机推荐

  1. git生成和添加SSH公钥

    一 .前言: 大家换电脑.换公司的时候,经常要关联本地git和git线上仓库, 在这里我就顺便记一下,好记性不如烂笔头, 以后找起来来方便 二 .查看自己是否生成过公钥,有的话可以直接拿过来用, 也可 ...

  2. Python入门-内置对象函数

    1.callable() 查看函数知否可调用,可调用返回True,不可用返回False print("input函数:", callable(input)) #input函数: T ...

  3. 帝国cms 7.5版列表页分页样式修改笔记

    最近在用帝国改版我的个人博客站点,这个也是我第一次尝试用帝国来做博客,之前用过wordpress,每用一个新的程序,都会有些新的收获,也会学到一些新的东西. 在改用帝国之前,我也在网上大概了解了一下, ...

  4. VUE(uni-app)+SSM 微信小程序

    环境 jdk:1.8.0_181 tomcat:7.0.100 mysql:8.0.25 工具 ideaIU+Hbuilder 遇到的问题 1.需要跳转到注册在tobar中页面时,需使用 uni.sw ...

  5. 初识gradle, idea+springboot Demo

    写在前面; 使用maven管理写过几个springboot的系统, 此篇博客纯属记录整理学习的过程. 另外, 源码分享地址在最后. Java: 1.8.0_281 tomcat: 1.8 IDE: I ...

  6. NodeJs学习日报day7——简单中间件

    const express = require('express') const app = express() const mw = function(req, resp, next) { cons ...

  7. Vue踩坑1——驼峰命名

    使用自定义Vue组件的时候,其他个方面都正常,但是浏览器就是显示不出自定义标签里的内容 <!DOCTYPE html> <html lang="en"> & ...

  8. Azure DevOps (十) 通过流水线完成Docker镜像的部署

    上一篇文章中,我们通过azure的流水线完成了镜像推送到镜像仓库中去,本篇文章我们继续开始完成下一步,通过流水线把镜像从仓库拉取到任意一台公网的服务器上去, 完成镜像部署的闭环. 首先我们需要先准备一 ...

  9. 2021.11.14 CF1583E Moment of Bloom(LCA+图上构造)

    2021.11.14 CF1583E Moment of Bloom(LCA+图上构造) https://www.luogu.com.cn/problem/CF1583E 题意: She does h ...

  10. IDEA打包javaFX及踩坑解决

    开门见山的说,先打包,再说坑. File-->Project Structure --> Artifacts-->(此处点加号)JAR-->From modules with ...