首页 > 编程语言 >java-框架-lombok

java-框架-lombok

时间:2024-06-04 23:29:23浏览次数:23  
标签:java String 框架 int private static lombok public name

1. @Data

@Data注解在类上,会为类的所有属性自动生成setter/getter、equals、canEqual、hashCode、toString方法,如为final属性,则不会为该属性生成setter

@Data
public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
}

2. @Getter/@Setter

如果觉得@Data太过残暴(因为@Data集合了@ToString、@EqualsAndHashCode、@Getter/@Setter、@RequiredArgsConstructor的所有特性)不够精细,可以使用@Getter/@Setter注解,此注解在属性上,可以为相应的属性自动生成Getter/Setter方法.

public class User {
    @Getter @Setter private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
}

3. @NonNull

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

import lombok.NonNull;
public class NonNullExample extends Something {
  private String name;
  
  public NonNullExample(@NonNull Person person) {
    super("Hello");
    this.name = person.getName();
  }
}

4. @Cleanup

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

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);
    }
  }
}

5. @EqualsAndHashCode

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

import lombok.EqualsAndHashCode;

@EqualsAndHashCode(exclude={"id", "shape"})
public class EqualsAndHashCodeExample {
  private transient int transientVar = 10;
  private String name;
  private double score;
  private Shape shape = new Square(5, 10);
  private String[] tags;
  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;
    }
  }
}

6. @ToString

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

通过将includeFieldNames参数设为true,就能明确的输出toString()属性。这一点是不是有点绕口,通过代码来看会更清晰些。

import lombok.ToString;

@ToString(exclude="id")
public class ToStringExample {
  private static final int STATIC_VAR = 10;
  private String name;
  private Shape shape = new Square(5, 10);
  private String[] tags;
  private int id;
  
  public String getName() {
    return this.getName();
  }
  
  @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;
    }
  }
}

7. @NoArgsConstructor, @RequiredArgsConstructor @AllArgsConstructor

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

@NoArgsConstructor将生成没有参数的构造函数。如果一个类仅仅只需要一个无参的构造函数,那么完全没有必要使用@NoArgsConstructor注解,因为Java会在编译时,为没有构造函数的类自动生成一个无参的构造函数。所以@NoArgsConstructor注解需要在已经存在构造函数时使用,才显得有意义。
————————————————
@RequiredArgsConstructor为每个需要特殊处理的字段生成一个带有1个参数的构造函数。所有未初始化的final字段以及标有@NonNull注解的字段。对于标有@NonNull注解的字段,还将生成一个显式的null检查。


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

8. @Value

@Value来表明一个类是不可变类

@Value
public class ValueExample {

    private  String name;
    private  int age;
}

public final class ValueExample {
    private final String name;
    private final int age;

    public ValueExample(final String name, final int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }

    public boolean equals(final Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof ValueExample)) {
            return false;
        } else {
            ValueExample other = (ValueExample)o;
            if (this.getAge() != other.getAge()) {
                return false;
            } else {
                Object this$name = this.getName();
                Object other$name = other.getName();
                if (this$name == null) {
                    if (other$name != null) {
                        return false;
                    }
                } else if (!this$name.equals(other$name)) {
                    return false;
                }

                return true;
            }
        }
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        int result = result * 59 + this.getAge();
        Object $name = this.getName();
        result = result * 59 + ($name == null ? 43 : $name.hashCode());
        return result;
    }

9. Builder

9.1. @Singular

只能应用于lombok已知的集合类型。目前,支持的类型有:

java.util:
Iterable, Collection, 和List (一般情况下,由压缩的不可修改的ArrayList支持).
Set, SortedSet, and NavigableSet (一般情况下,生成可变大小不可修改的HashSet或者TreeSet).
Map, SortedMap, and NavigableMap (一般情况下,生成可变大小不可修改的HashMap或者TreeMap).

Guava’s com.google.common.collect:
ImmutableCollection and ImmutableList
ImmutableSet and ImmutableSortedSet
ImmutableMap, ImmutableBiMap, and ImmutableSortedMap
ImmutableTable

9.1.1. @Builder.Default

@Builder
@ToString
public class BuilderBean {
    @Builder.Default
    private  String id= IdUtil.simpleUUID();
    @Builder.Default
    private long insertTime = System.currentTimeMillis();
    private String name;
    private String password;
    private Integer age;
    @Singular
    private List<String> hobbies;
}

      BuilderBean ss = BuilderBean.builder()
                .age(11)
                .name("ss")
                .password("****")
                .hobby("dd")
                .clearHobbies()
                .hobbies(Arrays.asList("ss","dfd"))
                .build();
        System.out.println(ss);

10. @SneakyThrows

public class SneakyThrowsExample {

    public static void main(String[] args) {
         test();
    }
    @SneakyThrows
    public  static  void  test(){
        String s=null;
        boolean dd = s.endsWith("dd");
    }
}
public class SneakyThrowsExample {
    public SneakyThrowsExample() {
    }

    public static void main(String[] args) {
        test();
    }

    public static void test() {
        try {
            String s = null;
            boolean var1 = ((String)s).endsWith("dd");
        } catch (Throwable var2) {
            throw var2;
        }
    }
}

11. @Synchronized

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

如果需要,可以自己创建这些锁。在$ lock和$ LOCK领域会当然不会,如果你已经自己原创生成的。您还可以通过将其指定为@Synchronized注释的参数来选择锁定另一个字段。在此用法变型中,不会自动创建字段,并且您必须自己明确创建它们,否则会发出错误。

public class SynchronizedExample {
    public static void main(String[] args) {
        heeselo();
    }
    @Synchronized
    public    void  heeelo(){
        System.out.println("Dd");
    }
    @Synchronized
    public static  void  heseelo(){
        System.out.println("Dd");
    }
    @Synchronized
    public static  void  heeselo(){
        System.out.println("Dd");
    }
}

public class SynchronizedExample {
    private final Object $lock = new Object[0];
    private static final Object $LOCK = new Object[0];

    public SynchronizedExample() {
    }

    public static void main(String[] args) {
        heeselo();
    }

    public void heeelo() {
        synchronized(this.$lock) {
            System.out.println("Dd");
        }
    }

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

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

12. Accessors

实体类的链式调用

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Book
{
    private Integer id;
    private String  bookName;
    private double  price;
    private String  author;
}

public class AccessorsDemo {
    public static void main(String[] args) {
        Book book = new Book();
        Book book1 = book.setBookName("ss").setAuthor("d").setPrice(3443L);
        System.out.println(book1);
    }
}

标签:java,String,框架,int,private,static,lombok,public,name
From: https://blog.csdn.net/qq_26594041/article/details/139455832

相关文章

  • eclipse引入lombok不生效问题
    遇到的问题在eclipse中使用lombok,省get/set方法,但是在新的环境中引入lombok.jar包并不生效,代码中有get方法就会飘红。原因:lombok在项目中没有生效,get/set也就没有。解决方法在D:\programTool\eclipse2019\eclipse.ini最后一行添加你lombok.jar所在的路径-javaagent:......
  • 基于Java的电影评论管理系统设计与实现(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示项目运行截图技术框架后端采用SpringBoot框架前端框架Vue可行性分析系统测试系统测试的目的系统功能测试数据库表设计代码参考数据库脚本为什么选择我?获取源码前言......
  • Java 变量
    Java了解变量1.为什么需要变量变量是程序的基本组成单位无论是使用哪种高级程序语音编写程序,变量都是其程序的基本组成单位比如://变量有三个基本要素(类型+名称+值)publicclassVar01{ publicstaticvoidmain(String[]args){ intnum1=1;//定义了......
  • java函数笔记
    Statement.executeQuery和Statement.executeUpdate作用:用于执行SQL查询和更新操作。问题:容易导致SQL注入攻击。解决方法:使用PreparedStatement进行参数化查询。//不安全的做法Statementstmt=connection.createStatement();ResultSetrs=stmt.executeQuery("SEL......
  • java 数值类型 强制转换注意
    数值类型分别为【byte】,【short】,【int】,【long】,【float】,【double】byte:最大值为127,最小值为-128;short:最大值为32767,最小值为-32768;int:最大值为2,147,483,647,最小值为-2,147,483,648;long:最大值为9,223,372,036,854,775,807,最小值为-9,223,372,036,854,7......
  • 一款WPF的精简版MVVM框架——stylet框架(MVVM绑定、依赖注入等)
    今天偶然知道一款叫做stylet的MVVM框架,挺小巧的,特别是它的命令触发方式,简单粗暴,让人感觉很巴适,现在我做一个简单的demo来顺便来分享给大家。本地创建一个WPF项目,此处我使用.NET8来创建。然后引用stylet最新的nuget包。 然后删掉App.xaml里面自带的启动项删掉以后: sty......
  • JavaScript省市区县选择三级联动实现
    <!DOCTYPEhtml><htmllang="en"><head> <metacharset="UTF-8"> <style>  .select-container{   margin:20pxauto;   width:610px;  }  select{   width:200px;   height:25px;  ......
  • 大学生HTML期末大作业——HTML+CSS+JavaScript美食网站(甜品)
    HTML+CSS+JS【美食网站】网页设计期末课程大作业web前端开发技术web课程设计网页规划与设计......
  • 大学生HTML期末大作业——HTML+CSS+JavaScript个人网站(图书爱好)
    HTML+CSS+JS【个人网站】网页设计期末课程大作业web前端开发技术web课程设计网页规划与设计......
  • (JAVA)设计模式-两阶段终止模式
    `publicclassTowPhaseTermination{publicThreadthread;publicvoidstart(){thread=newThread(newRunnable(){@Overridepublicvoidrun(){while(true){booleaninterrupted=Thread.currentThread().isIn......