IDEA set方法会return

今天看到项目中有个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();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值