序言
原来的开发中,使用lombok的一些常用注解,如@Data、@Setter、@Getter、@NoConstructor、@AllConstructor、@Value、@Builder、@ToString等简化开发,但是后面细看其实自己并不是完全会用它,其实这里面还是会有一些坑的,这里总结一下给大家。
依赖
首先要说的是依赖,pom中添加的依赖并不需要加版本号之类的,只需要把作用域设置为provided,代表打包的时候不会把它包进去,毕竟我们打的软件包越小越好。它只参与编译、测试、运行等周期。
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
其他作用域我也列出来
作用域(scope) | compile | test | runtime | provided | system |
---|---|---|---|---|---|
说明(description) | 默认作用域,强依赖。 | 表示依赖项目仅仅参与测试相关的工作,包括测试代码的编译,执行。比较典型的如junit | 表示被依赖项目无需参与编译过程,不过后期的测试和运行都需要参与其中。 | 表示打包时不需要将依赖项目打包进去。 | 与provided基本相同。但被依赖项目不会从maven仓库获取,而是直接从本地文件系统获取,需要配合systemPath属性使用。 |
val
lombok中不可变局部变量val相当于一种“类型”,用它可以替代本地final变量声明。
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();
}
}
var
var和val很类似,它被叫做无忧的局部变量,和val唯一的区别是它不会被final修饰,即不是不变的。
@NonNull
lombok的@NonNull注解用来标注方法的入参不为空,举个例子,
补充:区分几个NonNull的区别
- lombok.NonNull:@NonNull用在强制入参非空、属性非空的场景下,编译时会生成空指针检查的代码,如果不满足,则会抛出NullPointerException
- javax.annotation.NonNull:@NonNull用在返回结果不为空的场景,主要由IDE识别并给出警告提示
- javax.validation.constraints.NotNull:@NotNull主要用在Validator校验场景下,限制参数非空,如果不满足,则校验失败
public class NonNullExample {
public static void main(String[] args) {
test(null);
}
private static void test(@NonNull String str) {//str is marked non-null but is null
//如果下面校验了以下面为准
if (str == null) {
throw new NullPointerException("person is marked @NonNull but is null");
}
}
}
@Cleanup
@Cleanup注解用来自动释放io资源,跟try/finally的finally代码块做资源释放,或者try-with-resource语法糖的效果一样。
package com.hust.zhang.lombok;
import lombok.Cleanup;
import java.io.*;
public class CleanupExample {
public static void main(String[] args) throws IOException {
String path = "/Users/kaizhang/test/input.log";
@Cleanup BufferedReader reader = new BufferedReader(new FileReader(new File(path)));
String str;
while ((str = reader.readLine()) != null) {
System.out.println(str);
}
}
}
@Getter+@Setter
@Getter和@Setter注解应该非常熟悉了,比如创建MyObject对象,设置访问级别就可以控制创建出来的get、set方法的访问控制符。
package com.hust.zhang.lombok;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
public class MyObject {
/**
* name的@Setter注解访问级别为protected和访问控制符一样,
* 同包同类、同包不同类可以访问,不同包不同类就不能访问
*/
@Getter
@Setter(AccessLevel.PROTECTED)
private String name;
@Getter
@Setter
private int age = 10;
/**
* password的@Setter注解访问级别为私有时,
* 同包不同类就不能进行设置了,只能是同包同类可以访问setter方法
*/
@Setter(AccessLevel.PRIVATE)
@Getter
private String password;
}
@ToString
ToString注解有很多参数,@ToString.Exclude是@ToString注解内部注解,表明构造ToString方法时不会带上某个属性。@ToString的callSuper属性默认值是skip表明不会调用父类的ToString方法,call是表明会调用父类的ToString方法。includeFieldNames属性默认值就是true,这里写不写都一样,它会为每个字段生成一个toString的响应片段,格式为fieldName = fieldValue。其他需要使用时细看。
package com.hust.zhang.lombok;
import lombok.ToString;
public class ToStringExample {
static class Shape{
private int id;
private String name;
}
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;
}
}
}
@EqualsAndHashCode
@EqualsAndHashCode注解用来生成hashCode和equals方法。
补充:
- 为什么重写equals方法的同时要重写hashcode方法?
equals比较的是两个对象的内存地址,而hashcode则是根据内存地址经哈希算法获得,所以重写equals方法一定要重写hashcode方法。
- hashcode相同对象一定相同吗?什么时候需要重写Hashcode方法?
两个对象相等,则它们的hashcode一定相等。但是hashcode相等,对象不一定相等。因为hashcode是通过hash预映射,可能会存在hash碰撞问题。
如果两个对象不同,那么我们需要重写equal方法,即比较对象里的成员变量。但是还需要重写hashcode方法,未重写之前hashcode方法返回的是对象的32位JVM内存地址,不同地址的相同对象放进HashMap里面的时候它们不被看成是同一个对象,所以需要重写hashcode方法。
下面额外的属性和@ToString基本类似,这里就不赘述了。
package com.hust.zhang.lombok;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode
public class EqualsAndHashCodeExample {
static class Shape{
private int id;
private String name;
}
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;
}
}
}
@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor
这几个注解是用来创建构造函数的,@NoArgsConstructor无参构造函数,@AllArgsConstructor全参数构造函数,@RequiredArgsConstructor创建一个以staticName为名称的静态工厂方法,该方法围绕有参构造函数。
package com.hust.zhang.lombok;
import lombok.*;
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class ConstructorExample<T> {
private int x, y;
@NonNull private T description;
@NoArgsConstructor
public static class NoArgsExample {
@NonNull private String field;
}
}
可以写个main方法测试一下
public static void main(String[] args) {
ConstructorExample allConstructor = new ConstructorExample(13,14,Integer.valueOf(13));
ConstructorExample constructor = ConstructorExample.of(Integer.valueOf(13));
System.out.println(allConstructor.x+","+allConstructor.y+","+allConstructor.description);
System.out.println(constructor.x+","+constructor.y+","+constructor.description);
NoArgsExample noArgsExample = new ConstructorExample.NoArgsExample();
System.out.println(noArgsExample.field);
}
@Data、@Value、@Builder
@Data相当于把几个注解合并在一起,包括:@ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor!
@Value相当于是一个不变量,默认是private final,通常的应用场景是用来取配置文件中的某个属性给一个成员变量,@Value("${app.properties}")
@Builder注解为类生成复杂的生成器API,相当于使用了建造者设计模式,之后创建一个类可以使用调用链吧参数依次注入进对象。
@SnakeyThrows
@SnakeyThrows注解的作用相当于对异常进行了try-catch操作,这样就不需要在方法中捕获一场并抛出。
package com.hust.zhang.lombok;
import lombok.SneakyThrows;
import java.io.UnsupportedEncodingException;
public class SneakyThrowsExample implements Runnable {
@SneakyThrows(UnsupportedEncodingException.class)
public String utf8ToString(byte[] bytes) {
return new String(bytes, "UTF-8");
}
@Override
@SneakyThrows
public void run() {
throw new Throwable();
}
}
@Synchronized
@Synchronized是修饰同步方法的一个注解,正确的做法是不暴露我们自己的锁。下面给了一个例子,对count进行自增操作的方法是add(),对其加上@Synchronized表明这个方法就是线程安全的,实际上其实并不该这么做,synchronized虽然有jvm的锁优化-锁升级(根据竞争激烈程度从无锁->偏向锁->轻量级锁->重量级锁的过程,过程不可逆),一旦升级为重量级锁在性能上就差强人意了,一般都是使用原子类AtomicInteger来操作。
package com.hust.zhang.lombok;
import lombok.Synchronized;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class SynchronizedExample {
private final Object readLock = new Object();
private static volatile int count = 0;
@Synchronized
public static void add() {
count++;
}
@Synchronized("readLock")
public void foo() {
System.out.println("bar");
}
public static void main(String[] args) throws InterruptedException {
int cycle = 1000;
ThreadPoolExecutor executor = new ThreadPoolExecutor(100, 200,
30, TimeUnit.SECONDS, new LinkedBlockingDeque<>(100));
CountDownLatch countDownLatch = new CountDownLatch(cycle);
for (int i = 0; i < cycle; i++) {
executor.submit(() -> {
add();
countDownLatch.countDown();
});
}
countDownLatch.await();
System.out.println(count);
executor.shutdown();
}
}
@With
针对不可变属性的set,比较好的替代方法是构造对象的克隆,但是为这个字段提供一个新值。生成克隆的方法是通过@With注解来实现。
package com.hust.zhang.lombok;
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(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 NullPointerException("name");
}
return this.name == name ? this : new WithExample(name, age);
}
public static void main(String[] args) {
WithExample example = new WithExample("z", 13);
WithExample duplicate = example.withName("we");
System.out.println("name=" + example.name + ",age=" + example.age);
System.out.println("name=" + duplicate.name + ",age=" + duplicate.age);
}
}
@Getter(lazy=true)
@Getter(lazy=true)注解是private final修饰的变量进行懒加载,只有用到的时候才对其进行加载。
package com.hust.zhang.lombok;
import lombok.Getter;
public class GetterLazyExample {
@Getter(lazy=true) private final double[] cached = expensive();
private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
public static void main(String[] args) {
GetterLazyExample example = new GetterLazyExample();
//null
System.out.println(" cached value: " + example.cached);
//not null
System.out.println(" cached value: " + example.getCached());
}
}
@Log
其实原来也用过日志的组件,如SLF4J(Simple logging Facade for Java)+logback/log4j,其中SLF4j只是日志门面,即把不同的日志系统的实现进行了抽象化,只提供统一的日志接口。实现日志系统比较常见的就是logback和log4j。这些需要配合在一起使用,当然有时候添加的依赖多可能会出现日志实现系统的冲突,通过排包可以解决。那来看一下lombok的@Log注解。
package com.hust.zhang.lombok.logExample;
import lombok.extern.java.Log;
@Log
public class LogExample {
//@Log注解相当于在这定义了一个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");
}
}
太困了,后面慢慢补充... ...
其他补充:
- windows下配置好环境后可以通过echo %PATH%查看环境变量是否配好。
- IDEA在windows系统下通过shfit+F6可以统一修改变量名,在ios系统下按command+ctrl+g可以统一修改变量名。
参考链接: