02-Objects 和 MoreObjects
Posted 程序员008
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了02-Objects 和 MoreObjects相关的知识,希望对你有一定的参考价值。
JDK1.8之前Objects还是挺方便的,但是1.8之后JDK自带的Objects功能更加完善
import com.google.common.base.MoreObjects; import lombok.Data; import java.util.Objects; @Data public class Person { private String name; private int sex; private int age; public Person(String name, int sex, int age) { this.name = name; this.sex = sex; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return sex == person.sex && age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, sex, age); } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("name", this.getName()) .add("sex", this.getSex()) .add("age", this.getAge()) .toString(); } }
1.重写 hashCode 和 equals 方法很方便
重写 int hashCode() 方法方便
@Override
public int hashCode() {
return Objects.hash(name, sex, age);
}
重写 boolean equals(Object o) 方法方便
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return sex == person.sex && age == person.age && Objects.equals(name, person.name);
}
2.MoreObjects 重写 toString 方法
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("name", this.getName())
.add("sex", this.getSex())
.add("age", this.getAge())
.toString();
}
补充
MoreObjects 将对象格式化字符串
public void objToString() {
Person zs = new Person(null, 1, 28);
String nameStr = MoreObjects.toStringHelper(zs)
.omitNullValues()
.add("name", zs.getName())
.add("sex", zs.getSex())
.add("age", zs.getAge())
.toString();
System.out.println(nameStr.equals("Person{sex=1, age=28}"));
}
以上是关于02-Objects 和 MoreObjects的主要内容,如果未能解决你的问题,请参考以下文章
Caused by: java.lang.NoClassDefFoundError: com/google/common/base/MoreObjects