前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java开发神器Lombok的安装与使用

Java开发神器Lombok的安装与使用

作者头像
秃头哥编程
发布2019-06-17 15:44:58
5660
发布2019-06-17 15:44:58
举报
文章被收录于专栏:秃头哥编程

项目中经常使用bean,entity等类,绝大部分数据类类中都需要get、set、toString、equals和hashCode方法,虽然eclipse和idea开发环境下都有自动生成的快捷方式,但自动生成这些代码后,如果bean中的属性一旦有修改、删除或增加时,需要重新生成或删除get/set等方法,给代码维护增加负担。而使用了lombok则不一样,使用了lombok的注解(@Setter,@Getter,@ToString,@@RequiredArgsConstructor,@EqualsAndHashCode或@Data)之后,就不需要编写或生成get/set等方法,很大程度上减少了代码量,而且减少了代码维护的负担。故强烈建议项目中使用lombok,去掉bean中get、set、toString、equals和hashCode等方法的代码。

一、IDEA安装Lombok

安装过程如下图

安装完成后,重启IDEA即可。

二、在pom中添加依赖

代码语言:javascript
复制
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
    <scope>provided</scope>
</dependency>

三、Lombok常用注解

1、@Getter/@Setter注解为属性自动生成get/set方法。

代码语言:javascript
复制
@Setter
@Getter
public class User {
    private Long id;
    private String name;
    private String password;
    private String salt;
    private Integer status;
    private String address;
    private String phone;
    private Date lasttime;
}

2、@ToString注解,生成一个toString方法,默认的toString格式为:ClassName(fieldName= fieleValue ,fieldName1=fieleValue)。

代码语言:javascript
复制
@ToString
public class User {
    private Long id;
    private String name;
    private String password;
    private String salt;
    private Integer status;
    private String address;
    private String phone;
    private Date lasttime;
}

@ToString和下面的代码含义一样

代码语言:javascript
复制
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", salt='" + salt + '\'' +
                ", status=" + status +
                ", address='" + address + '\'' +
                ", phone='" + phone + '\'' +
                ", lasttime=" + lasttime +
                '}';
    }

3、Val将变量申明为final类型。

代码语言:javascript
复制
val defaultCount = new ArrayList<>();

// 下面的代码和上面的含义一样
final List<Integer> defaultCount = new ArrayList<>();

4、@NonNull注解能够为方法或构造函数的参数提供非空检查。

代码语言:javascript
复制
public void notNullExample(@NonNull String string) {
    //方法内的代码
}

//=>上面代码相当于如下:

public void notNullExample(String string) {
    if (string != null) {
        //方法内的代码相当于如下:
    } else {
        throw new NullPointerException("null");
    }
}

5、@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor,这几个注解分别自动生成了无参构造器、指定参数的构造器和包含所有参数的构造器。

代码语言:javascript
复制
@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; 
  } 

}

//上面代码相当于如下:
@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; 
  } 

}

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() { 
    } 
  } 
}

6、@Builder注解提供了一种比较推崇的构建值对象的方式。

代码语言:javascript
复制
@Builder 
public class BuilderExample { 

  private String name; 
  private int age; 

  @Singular private Set<String> occupations; 

}

//上面代码相当于如下:

public class BuilderExample { 

  private String name; 
  private int age; 
  private Set<String> occupations; 

  BuilderExample(String name, int age, Set<String> occupations) { 
    this.name = name; 
    this.age = age; 
    this.occupations = occupations; 
  } 

  public static BuilderExampleBuilder builder() { 
    return new BuilderExampleBuilder(); 
  } 

  public static class BuilderExampleBuilder { 

    private String name; 
    private int age; 
    private java.util.ArrayList<String> occupations;    

    BuilderExampleBuilder() { 
    } 

    public BuilderExampleBuilder name(String name) { 
      this.name = name; 
      return this; 
    } 

    public BuilderExampleBuilder age(int age) { 
      this.age = age; 
      return this; 
    } 

    public BuilderExampleBuilder occupation(String occupation) { 
      if (this.occupations == null) { 
        this.occupations = new java.util.ArrayList<String>(); 
      } 
      this.occupations.add(occupation); 
      return this; 
    } 

    public BuilderExampleBuilder occupations(Collection<? extends String> occupations) { 
      if (this.occupations == null) { 
        this.occupations = new java.util.ArrayList<String>(); 
      } 
      this.occupations.addAll(occupations); 
      return this; 
    } 

    public BuilderExampleBuilder clearOccupations() { 
      if (this.occupations != null) { 
        this.occupations.clear(); 
      }
      return this; 
    } 

    public BuilderExample build() {  
      Set<String> occupations = new HashSet<>(); 
      return new BuilderExample(name, age, occupations); 
    } 

    @verride 
    public String toString() { 
      return "BuilderExample.BuilderExampleBuilder(name = " + this.name + ", age = " + this.age + ", occupations = " + this.occupations + ")"; 
    } 
  } 
}

7、@Data注解作用比较全,其包含注解的集合@ToString,@EqualsAndHashCode,所有字段的@Getter和所有非final字段的@Setter, @RequiredArgsConstructor。其示例代码可以参考上面几个注解的组合。

8、@Synchronized注解类似Java中的Synchronized 关键字,但是可以隐藏同步锁。

代码语言:javascript
复制
public class SynchronizedExample { 

 private final Object readLock = new   Object(); 

 @Synchronized 
 public static void hello() { 
     System.out.println("world");   
 } 

 @Synchronized("readLock") 
 public void foo() { 
   System.out.println("bar"); 
 } 

//上面代码相当于如下:

 public class SynchronizedExample { 

  private static final Object $LOCK = new   Object[0]; 
  private final Object readLock = new   Object(); 

  public static void hello() { 
    synchronized($LOCK) { 
      System.out.println("world"); 
    } 
  }   

  public void foo() { 
    synchronized(readLock) { 
        System.out.println("bar");   
    } 
  } 

}

9、@Cleanup注解能够自动释放资源。

代码语言:javascript
复制
public   void jedisExample(String[] args) {
    try {
        @Cleanup Jedis jedis =   redisService.getJedis();
    } catch (Exception ex) {
        logger.error(“Jedis异常:”,ex)
    }

    //=>上面代码相当于如下:
    Jedis jedis= null;
    try {
        jedis = redisService.getJedis();
    } catch (Exception e) {
        logger.error(“Jedis异常:”,ex)
    } finally {
        if (jedis != null) {
            try {
                jedis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

10、@EqualsAndHashCode注解,自动生成equals和hashCode方法。

代码语言:javascript
复制
@EqualsAndHashCode(exclude = {"id"}, callSuper =true)
public class LombokDemo extends Demo{
    private int id;
    private String name;
    private String gender;
}

//上面代码相当于如下:

public class LombokDemo extends Demo{

    private int id;
    private String name;
    private String gender;
    
    @Override
    public boolean equals(final Object o) {
        if (o == this) return true;
        if (o == null) return false;
        if (o.getClass() != this.getClass()) return false;
        if (!super.equals(o)) return false;
        final LombokDemo other = (LombokDemo)o;
        if (this.name == null ? other.name != null : !this.name.equals(other.name)) return false;
        if (this.gender == null ? other.gender != null : !this.gender.equals(other.gender)) return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = result * PRIME + super.hashCode();
        result = result * PRIME + (this.name == null ? 0 : this.name.hashCode());
        result = result * PRIME + (this.gender == null ? 0 : this.gender.hashCode());
        return result;
    }

}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-06-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 秃头哥编程 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、IDEA安装Lombok
  • 二、在pom中添加依赖
  • 三、Lombok常用注解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档