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}"));
}

上一篇:linq


下一篇:使用pycharm开发Django2.2全过程(四)--数据库及模型层