---
title: "Lombok 之 Constructor"
author: "朱秋旭"
date: "2014-10-02T17:51:49Z"
tags: ["Java", "annotation", "lombok"]
categories: ["互联网"]
slug: "lombok-constructor"
draft: false
lastmod: "2014-10-03T15:28:36Z"
id: 2124409
url: "https://himichaelchu.iteye.com/blog/2124409"
---

LomBok 的相关目录已经整理出来，希望大家可以根据需求自助学习，好工具要大家分享：

[@Cleanup](/admin/blogs/2124327)     

[@Getter, @Setter](/admin/blogs/2124335)

[@ToString](/blog/2124349)

[@EqualsAndHashCode](/admin/blogs/2124353)

[@Constructor](/blog/2124409)

[@Data & @Value](/blog/2124577)

[@](/admin/blogs/2124582)[SneakyThrows](/admin/blogs/2124582)

[@Synchronized](/admin/blogs/2124584)

[@Getter(lazy=true)](/admin/blogs/2124588)

 

[@Log](/admin/blogs/2124589)

 

在Lombok中，生成构造方法的annotation一共有三个，@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsContructor。使用这三个annotation来完成项目中对于不同构造方法的需求。

 

@NoArgsConstructor ： 生成一个无参数的构造方法，这个annotation在与其他的annotation配合起来使用的时候更加能凸显出他的重要性，例如在使用hibernate这种框架的时候，如果有一个有参数的构造方法的时候，NoArgsConstructor会展示出他的作用。

 

@RequiredArgsConstructor： 会生成一个包含常量，和标识了NotNull的变量 的构造方法。生成的构造方法是private，如何想要对外提供使用可以使用staticName选项生成一个static方法。

 

@AllArgsContructor：  会生成一个包含所有变量，同时如果变量使用了NotNull annotation ， 会进行是否为空的校验， 我们来看一下官方给出的一个例子：

 

 

```
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.NonNull;

@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;
  }
}
```

 

 

上面的例子用Java代码翻译一下就是：

 

 

```
public class ConstructorExample<T> {
  private int x, y;
  @NonNull private T description;
  
  private ConstructorExample(T description) {
    if (description == null) throw new NullPointerException("description");
    this.description = description;
  }
  
  public static <T> ConstructorExample<T> of(T description) {
    return new ConstructorExample<T>(description);
  }
  
  @java.beans.ConstructorProperties({"x", "y", "description"})
  protected ConstructorExample(int x, int y, T description) {
    if (description == null) throw new NullPointerException("description");
    this.x = x;
    this.y = y;
    this.description = description;
  }
  
  public static class NoArgsExample {
    @NonNull private String field;
    
    public NoArgsExample() {
    }
  }
}
```

 如果是@AllArgsConstructor 在生成的构造函数上会生成一@ConstructorProperties 的Java annotation， 当然也可以通过将suppressConstructorProperties 设置为true来禁用@ConstructorProperties 。 如果你知道@ConstructorProperties 是干什么用的，那么一定就知道@NoArgsConstructor为什么没有这个配置参数了。

 

提示一点：@ConstructorProperties 只能用在JDK 6 中