首页 > 其他 > 详细

lombok中的@builder是怎么实现的?

时间:2019-12-30 11:50:03      阅读:197      评论:0      收藏:0      [点我收藏+]

比如有个Aliyun类,其中有以下几个属性:appKey,appSecret,bucket,endPoint。使用lombok的时候我们只需要加上一个@Builder注解就可以使用建造者模式构建对象。

那么这个@builder是怎样做到的呢?以下demo基本是他的原理了。

public class Aliyun {
  private String appKey;
  private String appSecret;
  private String bucket;
  private String endPoint;

  public static class Builder{
    private String appKey;
    private String appSecret;
    private String bucket;
    private String endPoint;

    public Builder appKey(String appKey) {
      this.appKey = appKey;
      return this;
    }

    public Builder appSecret(String appSecret) {
      this.appSecret = appSecret;
      return this;
    }

    public Builder bucket(String bucket) {
      this.bucket = bucket;
      return this;
    }

    public Builder endPoint(String endPoint) {
      this.endPoint = endPoint;
      return this;
    }

    public Aliyun build() {
      return new Aliyun(this);
    }

  }

  public static Builder builder() {
    return new Aliyun.Builder();
  }

  private Aliyun(Builder builder) {
    this.appKey = builder.appKey;
    this.appSecret = builder.appSecret;
    this.bucket = builder.bucket;
    this.endPoint = builder.endPoint;
  }

  @Override
  public String toString() {
    return "Aliyun{" +
        "appKey=‘" + appKey + ‘\‘‘ +
        ", appSecret=‘" + appSecret + ‘\‘‘ +
        ", bucket=‘" + bucket + ‘\‘‘ +
        ", endPoint=‘" + endPoint + ‘\‘‘ +
        ‘}‘;
  }
}

 

在使用上是一样的:

Aliyun aliyun = Aliyun.builder()
    .appKey("123")
    .appSecret("456")
    .bucket("789")
    .endPoint("0")
    .build();
System.out.println(aliyun);

lombok中的@builder是怎么实现的?

原文:https://www.cnblogs.com/chichung/p/12118395.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!