这篇文章主要介绍Lombok中的@Builder注解怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
@Builder注解的作用主要是用来生成对象,并且可以为对象链式赋值。
因为@Builder注解是lombok中的东西,所以第一步我们需要引入lombok的依赖,如下图:
第二步我们需要给我们的实体类加上一个@Builder注解,如下图:
实体类加上@Builder注解之后,编译之后会多出一个builder()方法,和一个CardBuilder静态内部类,如下图:
代码如下:
public class Card { private int id; private String name; private boolean sex; public static Card.CardBuilder builder() { return new Card.CardBuilder(); } public Card(int id, String name, boolean sex) { this.id = id; this.name = name; this.sex = sex; } public Card() { } public int getId() { return this.id; } public String getName() { return this.name; } public boolean isSex() { return this.sex; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setSex(boolean sex) { this.sex = sex; } public boolean equals(Object o) { if (o == this) { return true; } else if (!(o instanceof Card)) { return false; } else { Card other = (Card)o; if (!other.canEqual(this)) { return false; } else if (this.getId() != other.getId()) { return false; } else { Object this$name = this.getName(); Object other$name = other.getName(); if (this$name == null) { if (other$name == null) { return this.isSex() == other.isSex(); } } else if (this$name.equals(other$name)) { return this.isSex() == other.isSex(); } return false; } } } protected boolean canEqual(Object other) { return other instanceof Card; } public int hashCode() { int PRIME = true; int result = 1; int result = result * 59 + this.getId(); Object $name = this.getName(); result = result * 59 + ($name == null ? 43 : $name.hashCode()); result = result * 59 + (this.isSex() ? 79 : 97); return result; } public String toString() { return "Card(id=" + this.getId() + ", name=" + this.getName() + ", sex=" + this.isSex() + ")"; } public static class CardBuilder { private int id; private String name; private boolean sex; CardBuilder() { } public Card.CardBuilder id(int id) { this.id = id; return this; } public Card.CardBuilder name(String name) { this.name = name; return this; } public Card.CardBuilder sex(boolean sex) { this.sex = sex; return this; } public Card build() { return new Card(this.id, this.name, this.sex); } public String toString() { return "Card.CardBuilder(id=" + this.id + ", name=" + this.name + ", sex=" + this.sex + ")"; } } }
以上是“Lombok中的@Builder注解怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。