今天看到项目中有个return语句的结尾是set方法,很是奇怪
//lombok写法
public static <T> ResultTO<T> OK(T data) {
return new ResultTO<T>(data).setMessage("操作成功");
}
//常规写法
public static <T> ResultTO<T> OK(T data) {
ResultTO<T> result = new ResultTO<T>(data);
result.setMessage("操作成功");
return result;
}
写了个main方法去测试,不管怎么测都没问题。然后看了下注解
@Data
@Accessors(chain = true)
注解使用了自动生成常规方法,以及对set/get属性控制,不得不惊叹现在注解太强大了。
不过没有十全十美的事,注解强大使代码简洁不可否认,但是也降低的代码的可读性。
以下介绍@Accessors注解,有三个属性,fluent,chain,prefix
public @interface Accessors {
/**
* If true, accessors will be named after the field and not include a <code>get</code> or <code>set</code>
* prefix. If true and <code>chain</code> is omitted, <code>chain</code> defaults to <code>true</code>.
* <strong>default: false</strong>
*/
boolean fluent() default false;
/**
* If true, setters return <code>this</code> instead of <code>void</code>.
* <strong>default: false</strong>, unless <code>fluent=true</code>, then <strong>default: true</code>
*/
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.
*/
String[] prefix() default {};
}
1.fluent:默认为false。当该值为 true 时,对应字段的 getter 方法前面就没有 get,setter 方法就不会有 set。
@Accessors(fluent = true)
@Data
@Accessors(fluent = true)
public class Test {
private String name;
private int age;
public static void main(String[] args) {
Test a = new Test();
a.name("zhangsan");
a.age(18);
}
}
2.chain:默认为false,当该值为 true 时,对应字段的 setter 方法调用后,会返回当前对象
@Data
@Accessors(chain = true)
public class Test {
private String name;
private int age;
public static void main(String[] args) {
Test a = new Test();
Test b = a.setAge(18);
}
}
prefix:属性是一个字符串数组,当该数组有值时,表示忽略字段中对应的前缀,生成对应的 getter 和 setter 方法
@Data
@Accessors(prefix = {"aa","bb"})
public class Test {
private String aaName;
private int bbAge;
public static void main(String[] args) {
Test a = new Test();
a.setName("33");
a.getName();
a.setAge(18);
a.getAge();
}
}