栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

lombok

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

lombok

lombok 介绍
Lombok项目是一个Java库,它会自动插入您的编辑器和构建工具中,从而为您的Java增光添彩。
让代码变得更简洁,但可读性和阅读性会变弱。
配置 1、pom.xml文件配置

    org.projectlombok
    lombok
    1.18.22
    provided

2、cmd相关
1).得到lombok在Maven仓库的路径D:javarepoorgprojectlomboklombok1.18.22
2).cmd命令:java -jar D:javarepoorgprojectlomboklombok1.18.22lombok-1.18.22.jar
3、编辑器相关

选择eclipse安装路径D:javaeclipse

4、安装后相关
1).D:javaeclipse下有lombok.jar,eclipse.ini文件自动增加1行-javaagent:D:javaeclipselombok.jar
2).重启eclipse
使用 @NoArgsConstructor,@RequiredArgsConstructor,@AllArgsConstructor

无参构造器、部分参数构造器、全参构造器。Lombok没法实现多种参数构造器的重载。

示例

lombok示例代码如下

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

@AllArgsConstructor
@RequiredArgsConstructor
@NoArgsConstructor
public class TestConstructor {	
	@NonNull private String name;
	private int age;
	private int score;
}

不使用lombok示例代码如下

import lombok.NonNull;

public class TestConstructor {
  @NonNull
  private String name;  
  private int age; 
  private int score;  
  public TestConstructor(@NonNull String name, int age, int score) {
    if (name == null)
      throw new NullPointerException("name is marked non-null but is null"); 
    this.name = name;
    this.age = age;
    this.score = score;
  }  
  public TestConstructor(@NonNull String name) {
    if (name == null)
      throw new NullPointerException("name is marked non-null but is null"); 
    this.name = name;
  }  
  public TestConstructor() {}  
}
@Getter/@Setter

@Getter/@Setter注解,此注解在属性上,可以为相应的属性自动生成Getter/Setter方法

示例

lombok示例代码如下

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class TestSetterGetter {	
	private String name;
	private int age;
	private int score;
	@Getter(lazy = true) private final double[] cached = calc();
	
	private double[] calc() {
        double[] result = new double[10];
        for (int i = 1; i < result.length; i++) {
            result[i] = Math.sin(i);
        }
        return result;
    }
}

不使用lombok示例代码如下

import java.util.concurrent.atomic.AtomicReference;

public class TestSetterGetter {
  private String name;  
  private int age; 
  private int score;
  
  public void setName(String name) {
    this.name = name;
  }
  
  public void setAge(int age) {
    this.age = age;
  }
  
  public void setScore(int score) {
    this.score = score;
  }
  
  public String getName() {
    return this.name;
  }
  
  public int getAge() {
    return this.age;
  }
  
  public int getScore() {
    return this.score;
  }
  
  private final AtomicReference cached = new AtomicReference();
  
  public double[] getCached() {
    Object value = this.cached.get();
    if (value == null)
      synchronized (this.cached) {
        value = this.cached.get();
        if (value == null) {
          double[] actualValue = calc();
          value = (actualValue == null) ? this.cached : actualValue;
          this.cached.set(value);
        } 
      }  
    return (value == this.cached) ? null : (double[])value;
  }
  
  private double[] calc() {
    double[] result = new double[10];
    for (int i = 1; i < result.length; i++)
      result[i] = Math.sin(i); 
    return result;
  }
}
 
@ToString 

类使用@ToString注解,Lombok会生成一个toString()方法,默认情况下,会输出类名、所有属性(会按照属性定义顺序),用逗号来分割。

示例

lombok示例代码如下

import lombok.ToString;

class tmp{
	private String info = "父类info";
	@Override
	public String toString() {
		return "tmp [info=" + info + "]";
	}		
}
@ToString(onlyExplicitlyIncluded=true)
public class TestToString extends tmp{	
	@ToString.Include(name="test")private String name;
	@ToString.Include(rank=1) private int age;
	@ToString.Include(rank=2) private int score;
}

不使用lombok示例代码如下

class tmp {
  private String info = "; 
  public String toString() {
    return "tmp [info=" + this.info + "]";
  }
}
public class TestToString extends tmp {
  private String name; 
  private int age; 
  private int score;
    
  public String toString() {
    return "TestToString(score=" + getScore() + ", age=" + getAge() + ", test=" + getName() + ")";
  } 
}
@EqualsAndHashCode

默认情况下,会使用所有非静态(non-static)和非瞬态(non-transient)属性来生成equals和hasCode,也能通过exclude注解来排除一些属性。

示例

lombok示例代码如下

import lombok.EqualsAndHashCode;

@EqualsAndHashCode
public class TestEqualsAndHashCode {	
	private String name;
	private int age;
	private int score;
}

不使用lombok示例代码如下

public class TestEqualsAndHashCode {
  private String name;
  private int age; 
  private int score;
  
  public boolean equals(Object o) {
    if (o == this)
      return true; 
    if (!(o instanceof TestEqualsAndHashCode))
      return false; 
    TestEqualsAndHashCode other = (TestEqualsAndHashCode)o;
    if (!other.canEqual(this))
      return false; 
    if (this.age != other.age)
      return false; 
    if (this.score != other.score)
      return false; 
    Object this$name = this.name, other$name = other.name;
    return !((this$name == null) ? (other$name != null) : !this$name.equals(other$name));
  }
  
  protected boolean canEqual(Object other) {
    return other instanceof TestEqualsAndHashCode;
  }
  
  public int hashCode() {
    int PRIME = 59;
    result = 1;
    result = result * 59 + this.age;
    result = result * 59 + this.score;
    Object $name = this.name;
    return result * 59 + (($name == null) ? 43 : $name.hashCode());
  }
}
@Data

整合包,只要加了 @Data 这个注解,等于同时加了以下注解

  • @Getter/@Setter
  • @ToString
  • @EqualsAndHashCode
  • @RequiredArgsConstructor

如为final属性,则不会为该属性生成setter方法。

示例

lombok示例代码如下

import lombok.Data;
import lombok.NonNull;

@Data
public class TestData {	
	@NonNull private String name;
	private int age;
	private int score;
	private final String test = "test";
}

不使用lombok示例代码如下

import lombok.NonNull;

public class TestData {
  @NonNull
  private String name; 
  private int age; 
  private int score;
  private final String test = "test";
    
  public TestData(@NonNull String name) {
    if (name == null)
      throw new NullPointerException("name is marked non-null but is null"); 
    this.name = name;
  }
  
  public String toString() {
    return "TestData(name=" + getName() + ", age=" + getAge() + ", score=" + getScore() + ", test=" + getTest() + ")";
  }
  
  public int hashCode() {
    int PRIME = 59;
    result = 1;
    result = result * 59 + getAge();
    result = result * 59 + getScore();
    Object $name = getName();
    result = result * 59 + (($name == null) ? 43 : $name.hashCode());
    Object $test = getTest();
    return result * 59 + (($test == null) ? 43 : $test.hashCode());
  }
  
  protected boolean canEqual(Object other) {
    return other instanceof TestData;
  }
  
  public boolean equals(Object o) {
    if (o == this)
      return true; 
    if (!(o instanceof TestData))
      return false; 
    TestData other = (TestData)o;
    if (!other.canEqual(this))
      return false; 
    if (getAge() != other.getAge())
      return false; 
    if (getScore() != other.getScore())
      return false; 
    Object this$name = getName(), other$name = other.getName();
    if ((this$name == null) ? (other$name != null) : !this$name.equals(other$name))
      return false; 
    Object this$test = getTest(), other$test = other.getTest();
    return !((this$test == null) ? (other$test != null) : !this$test.equals(other$test));
  }
  
  public void setScore(int score) {
    this.score = score;
  }
  
  public void setAge(int age) {
    this.age = age;
  }
  
  public void setName(@NonNull String name) {
    if (name == null)
      throw new NullPointerException("name is marked non-null but is null"); 
    this.name = name;
  }
  
  public String getTest() {
    return "test";
  }
  
  public int getScore() {
    return this.score;
  }
  
  public int getAge() {
    return this.age;
  }
  
  @NonNull
  public String getName() {
    return this.name;
  }
}
@NonNull

该注解用在属性或构造器上,Lombok会生成一个非空的声明,可用于校验参数,能帮助避免空指针。

示例

lombok示例代码如下

import lombok.NonNull;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class TestNonNull {	
	@NonNull private String name;
	private int age;
	private int score;
	
	public String test(@NonNull String teacher) {
		return "name:" + name + "n" + "teacher:" + teacher;
	}
}

不使用lombok示例代码如下

import lombok.NonNull;

public class TestNonNull {
  @NonNull
  private String name; 
  private int age; 
  private int score;
  
  public TestNonNull(@NonNull String name) {
    if (name == null)
      throw new NullPointerException("name is marked non-null but is null"); 
    this.name = name;
  }
  
  public String test(@NonNull String teacher) {
    if (teacher == null)
      throw new NullPointerException("teacher is marked non-null but is null"); 
    return "name:" + this.name + "n" + "teacher:" + teacher;
  }  
}
@Cleanup

该注解能帮助我们自动调用close()方法,很大的简化了代码。

示例

lombok示例代码如下

import lombok.Cleanup;

public class TestCleanup {

	public int noParamSqlUpdate(String noParamSql) throws Exception {	
		@Cleanup Connection con = getConnection();
		//发送sql语句
		@Cleanup PreparedStatement ps = con.prepareStatement(noParamSql);
		int count = ps.executeUpdate();	
		//关闭连接
		//@Cleanup完成	
		return count;
	}
}

不使用lombok示例代码如下

public class TestCleanup {
  
  public int noParamSqlUpdate(String noParamSql) throws Exception {
    Connection con = getConnection();
    try {
      Exception exception;
      PreparedStatement ps = con.prepareStatement(noParamSql);
      try {
        int count = ps.executeUpdate();
        int i = count;
        if (Collections.singletonList(ps).get(0) != null)
          ps.close(); 
        return i;
      } finally {}
      if (Collections.singletonList(ps).get(0) != null)
        ps.close(); 
      throw exception;
    } finally {
      if (Collections.singletonList(con).get(0) != null)
        con.close(); 
    } 
  }
}
@Synchronized

@Synchronized是synchronized方法修饰符的更安全的变体。与一样synchronized,注释只能在静态方法和实例方法上使用。它的操作类似于synchronized关键字,但是它锁定在不同的对象上。关键字锁定在上this,但注解锁定在名为$ lock的字段上,该字段是私有的。

示例

lombok示例代码如下

import lombok.Synchronized;

public class TestSynchronized {
	//从连接池借连接
	@Synchronized
	private static Connection getConnection() throws Exception {
		return pool.getConnection();
	}
}	

不使用lombok示例代码如下

public class TestSynchronized {
  private static final Object $LOCK = new Object[0];
  
  private static Connection getConnection() throws Exception {
    synchronized ($LOCK) {
      return pool.getConnection();
    } 
  }
}
@Value

整合包,但是他会把所有的变量都设成 final 的,其他的就跟 @Data 一样,等于同时加了以下注解

  • @Getter (注意没有setter)
  • @ToString
  • @EqualsAndHashCode
  • @AllArgsConstructor
示例

lombok示例代码如下

import lombok.Value;

@Value
public class TestValue {	
	private String name;
	private int age;
	private int score;
}

不使用lombok示例代码如下

public final class TestValue {
  private final String name;  
  private final int age; 
  private final int score;
  
  public TestValue(String name, int age, int score) {
    this.name = name;
    this.age = age;
    this.score = score;
  }
  
  public String toString() {
    return "TestValue(name=" + getName() + ", age=" + getAge() + ", score=" + getScore() + ")";
  }
  
  public int hashCode() {
    int PRIME = 59;
    result = 1;
    result = result * 59 + getAge();
    result = result * 59 + getScore();
    Object $name = getName();
    return result * 59 + (($name == null) ? 43 : $name.hashCode());
  }
  
  public boolean equals(Object o) {
    if (o == this)
      return true; 
    if (!(o instanceof TestValue))
      return false; 
    TestValue other = (TestValue)o;
    if (getAge() != other.getAge())
      return false; 
    if (getScore() != other.getScore())
      return false; 
    Object this$name = getName(), other$name = other.getName();
    return !((this$name == null) ? (other$name != null) : !this$name.equals(other$name));
  }
  
  public int getScore() {
    return this.score;
  }
  
  public int getAge() {
    return this.age;
  }
  
  public String getName() {
    return this.name;
  }
}
@SneakyThrows

@SneakyThrows用的并不多,因为只是将异常抛出throw,还是需要你在调用方法时对异常做处理。它只是一个try-catch的简单写法。

示例

lombok示例代码如下

import lombok.SneakyThrows;

public class TestSneakyThrows {
	
	@SneakyThrows(Exception.class)
	public void calc() {
		int a = 1;
		System.out.println(a/0);
	}
}

不使用lombok示例代码如下

public class TestSneakyThrows {
 
  public void calc() {
    try {
      int a = 1;
      System.out.println(a / 0);
    } catch (Exception $ex) {
      throw $ex;
    } 
  }
}
@With

作用于类,生成多个 with + 变量名的方法(个数为所有成员变量,不包含 @NonNull),作用于变量,生成 with + 变量名的方法,返回当前对象,需要提供全参(不包含静态变量)构造方法

示例

lombok示例代码如下

import lombok.AllArgsConstructor;
import lombok.With;

@With
@AllArgsConstructor
public class TestWith {	
	@With private String name;
	private int age;
	private int score;
}

不使用lombok示例代码如下

public class TestWith {
  private String name; 
  private int age; 
  private int score;
  
  public TestWith withAge(int age) {
    return (this.age == age) ? this : new TestWith(this.name, age, this.score);
  }
  
  public TestWith withScore(int score) {
    return (this.score == score) ? this : new TestWith(this.name, this.age, score);
  }
  
  public TestWith(String name, int age, int score) {
    this.name = name;
    this.age = age;
    this.score = score;
  }
  
  public TestWith withName(String name) {
    return (this.name == name) ? this : new TestWith(name, this.age, this.score);
  }
}
@Builder

@Builder注解 可以很方便的使用构造模式

示例

lombok示例代码如下

import lombok.Builder;

@Builder
public class TestBuilder {	
	private String name;
	private int age;
	private int score;

	public static void main(String[] args) {
		TestBuilderBuilder testBuilderBuilder = TestBuilder.builder();
		
		testBuilderBuilder.name("zhangsan");
		testBuilderBuilder.age(20);
		testBuilderBuilder.score(100);

		TestBuilder testBuilder = testBuilderBuilder.build();				
	}
}

不使用lombok示例代码如下

public class TestBuilder {
  private String name;
  private int age; 
  private int score;
  
  public static TestBuilderBuilder builder() {
    return new TestBuilderBuilder();
  }
  
  TestBuilder(String name, int age, int score) {
    this.name = name;
    this.age = age;
    this.score = score;
  }
  
  public static class TestBuilderBuilder {
    private String name;
    private int age; 
    private int score;
    
    public TestBuilderBuilder name(String name) {
      this.name = name;
      return this;
    }
    
    public TestBuilderBuilder age(int age) {
      this.age = age;
      return this;
    }
    
    public TestBuilderBuilder score(int score) {
      this.score = score;
      return this;
    }
    
    public TestBuilder build() {
      return new TestBuilder(this.name, this.age, this.score);
    }
    
    public String toString() {
      return "TestBuilder.TestBuilderBuilder(name=" + this.name + ", age=" + this.age + ", score=" + this.score + ")";
    }
  }
  
  public static void main(String[] args) {
    TestBuilderBuilder testBuilderBuilder = builder();
    testBuilderBuilder.name("zhangsan");
    testBuilderBuilder.age(20);
    testBuilderBuilder.score(100);
    TestBuilder testBuilder = testBuilderBuilder.build();
  }
}
turn this;
    }
    
    public TestBuilderBuilder age(int age) {
      this.age = age;
      return this;
    }
    
    public TestBuilderBuilder score(int score) {
      this.score = score;
      return this;
    }
    
    public TestBuilder build() {
      return new TestBuilder(this.name, this.age, this.score);
    }
    
    public String toString() {
      return "TestBuilder.TestBuilderBuilder(name=" + this.name + ", age=" + this.age + ", score=" + this.score + ")";
    }
  }
  
  public static void main(String[] args) {
    TestBuilderBuilder testBuilderBuilder = builder();
    testBuilderBuilder.name("zhangsan");
    testBuilderBuilder.age(20);
    testBuilderBuilder.score(100);
    TestBuilder testBuilder = testBuilderBuilder.build();
  }
}
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号