前言

今天在看GitHub某大神写的代码的时候看到一个标签并没有使用过,所有百度了一下使用方法在此记录一下。

@Accessors

Accessor的中文含义是存取器,@Accessors用于配置getter和setter方法的生成结果。

源代码:

@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.SOURCE)
public @interface Accessors {
    /**
     * If true, accessors will be named after the field and not include a {@code get} or {@code set}
     * prefix. If true and {@code chain} is omitted, {@code chain} defaults to {@code true}.
     * <strong>default: false</strong>
     * 
     * @return Whether or not to make fluent methods (named {@code fieldName()}, not for example {@code setFieldName}).
     */
    boolean fluent() default false;
    
    /**
     * If true, setters return {@code this} instead of {@code void}.
     * <strong>default: false</strong>, unless {@code fluent=true}, then <strong>default: true</strong>
     * 
     * @return Whether or not setters should return themselves (chaining) or {@code void} (no chaining).
     */
    boolean chain() default false;
    
    /**
     * If present, only fields with any of the stated prefixes are given the getter/setter treatment.
     * Note that a prefix only counts if the next character is NOT a lowercase character or the last
     * letter of the prefix is not a letter (for instance an underscore). If multiple fields
     * all turn into the same name when the prefix is stripped, an error will be generated.
     * 
     * @return If you are in the habit of prefixing your fields (for example, you name them {@code fFieldName}, specify such prefixes here).
     */
    String[] prefix() default {};
}

此注解可以使用在方法上还有类上。
可以看到一共有3个属性,下面单独记录一下各个属性区别。

chain

chain的中文含义是链式的,设置为true,则setter方法返回当前对象.
WX20191115-143513@2x.png

fluent

fluent的时候:getter和setter方法的方法名都是基础属性名,且setter方法返回当前对象。生成的方法没有get/set名字。
WX20191115-144007@2x.png

prefix

生成getter和setter方法的字段名会忽视指定前缀。可以看到生产的方法中没有job这个前缀了。
123.png


发飙的蜗牛
19 声望3 粉丝

引用和评论

0 条评论