@With,@Accessors(chanins=true),@ExtensionMethod——Lombok常用注解

一、@With(很少用)

这个注解可以用在类上也可以用在单个的成员变量上,使lombok构建一个’with’ -一个withX方法,它会生成该对象的克隆。
这里做了一个实验,是浅拷贝,不是深拷贝。

@AllArgsConstructor
@ToString
public class Aoo {
    
    
    @With(AccessLevel.PUBLIC)
    private String attr1;

    @With(AccessLevel.PUBLIC)
    private String attr2;
}
 public static void main(String[] args) {
    
    
      Aoo aoo = new Aoo("sss","sss");
      System.out.println(aoo.hashCode()+"原始hashCode");
      aoo.withAttr1("aaa");
      System.out.println(aoo+"---");
      System.out.println(aoo.hashCode()+"克隆后的hashCode");
  }

在这里插入图片描述

二、 @Accessors(非常好用)

一个用于生成getter、setter和“with”-的设置容器
@Accessors有四个属性,只说两个,有两个不太看得懂。

(一)fluent (布尔型)

如果为true,让set和get变得更加优雅。如果为true则chain默认为true。
这个设置对@With没有影响;他们总是有一个“with”的前缀。

@Accessors(fluent = true)
@Data
@AllArgsConstructor
public class Aoo {
    
    

    private String attr1;

    private String attr2;

}
 public static void main(String[] args) {
    
    
    Aoo aoo = new Aoo("sss","aaa");
    // 不需要使用get,直接属性名就可以get到。
    aoo.attr1();
    aoo.attr2();
    // 不需要使用set,直接设置即可
    aoo.attr1("attr1").attr2("attr2");
}

(二)chain (布尔型)

set方法是否返回一个值,如果chain为真,则返回这个对象自己,如果chain为假,则返回值为void

@Accessors(chain = true)
@Data
public class Aoo {
    
    

    private String attr1;

    private String attr2;

}
public static void main(String[] args) {
    
    
    Aoo aoo = new Aoo().setAttr1("sss").setAttr2("sss");
    Aoo boo = aoo.setAttr2("aaaa").setAttr2("bbbb");
    System.out.println(boo.toString());
}

三、@ExtensionMethod(实验阶段)

向现有类型添加新方法

@ExtensionMethod({
    
    java.util.Arrays.class,java.util.Date.class})
public class Test {
    
    

    public static void main(String[] args) {
    
    
        int[] array = new int[]{
    
    10,2,6,1,5};
        array.sort();
        // 如果没有使用ExtensionMethod,那么应该这样写
        // Arrays.sort(array);
        System.out.println(array.toString());
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44712778/article/details/129543929
今日推荐