@Accessors使用和详解

一、什么是@Accessors注解?

@RequiredArgsConstructor是Lombok的一个注解,简化了我们对setter和getter方法操作它可以作用在类上,也可以作用在类的单个属性上。修饰类的时候对这个类的所有属性都是有效的,修饰单个属性的时候,只对当前的属性有效。

二、@Accessors导包

<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.22</version>
</dependency>

三、@Accessors源码讲解和使用案例

 从源码可以知道,该注解有三个属性,分别是fluent,chain,prefix。其中,fluent和chain是boolean类型,默认值都是false,prefix是数组类型,默认值为空。

  • fluent:默认值为false,当该值为true时,省略对象赋值和取值的set和get前缀
@Data
@Accessors(fluent = true)
public class Animal {

    String name;
    Integer age;

    public static void main(String[] args) {
        Animal animal = new Animal();
        //赋值的时候省略了前缀set
        animal.name("狗");
        //取值的时候省略了前缀get
        String animalName = animal.name();
        System.out.println(animalName);
    }
}

 

  • chain:默认值为false,当该值为true时,对应字段的setter方法调用后,会返回当前对象
@Data
@Accessors(chain = true)
public class Animal {

    String name;
    Integer age;

    public static void main(String[] args) {
        //new出的对象直接赋值,返回当前对象
        Animal animal = new Animal().setName("狗").setAge(2);
        System.out.println("直接返回当前对象:"+animal.toString());
    }
}

 

  • prefix:该属性是一个字符串数组,默认值为空,该数组有值的时候,表示忽略字段对应的前缀,生成对应的getter和setter方法
@Data
@Accessors(prefix = {"aa", "bb"})
public class Animal {

    String aaName;
    Integer bbAge;

    public static void main(String[] args) {
        Animal animal = new Animal();
        //忽略了前缀aa进行赋值
        animal.setName("狗");
        //忽略了前缀bb进行赋值
        animal.setAge(2);
        System.out.println("忽略了前缀aa和bb:" + animal.toString());

    }
}

猜你喜欢

转载自blog.csdn.net/qq_36138652/article/details/134392109