Common usage and implementation of guava Objects

Objects are mainly used to override toString and HashCode methods. There is also a method firstNonNull(T, T) which returns one of the two values ​​that is not null if both are null. Throws a null pointer exception.

See the usage of the code above:

import com.google.common.base.Objects;

public class ObjectsLearn {
	private Integer id;
	private String name;
	private String address;
	
	public ObjectsLearn(Integer id, String name, String address) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		//return "ObjectsLearn [id=" + id + ", name=" + name + ", address=" + address + "]";
		return Objects.toStringHelper(this).omitNullValues().add("id", id).add("name", name).add("address", address).toString();
	}
	
	@Override
	public int hashCode() {
		return Objects.hashCode(id,name,address);
	}
	public static void main(String[] args) {
		ObjectsLearn learn = new ObjectsLearn(1, "test", "天上");
		System.out.println(learn);
	}
}


Take a look at the source code record of Objects.toStringHelper(this).omitNullValues().add("id", id).add("name", name).add("address", address).toString() Next:
Objects This piece of code is implemented in a linked list structure:
public static final class ToStringHelper {
    private final String className;
    private final ValueHolder holderHead = new ValueHolder();
    private ValueHolder holderTail = holderHead;
    private boolean omitNullValues = false;

Defines the head holderHead of a linked list;

private ValueHolder addHolder() {
      ValueHolder valueHolder = new ValueHolder();
      holderTail = holderTail.next = valueHolder;
      return valueHolder;
    }
This piece of code points to the next node;

private ToStringHelper addHolder(String name, @ Nullable Object value) {
      ValueHolder valueHolder = addHolder();
      valueHolder.value = value;
      valueHolder.name = checkNotNull(name);
      return this;
    }
This piece of code first calls addHolder to point to the next node, and then assigns a value to the next node.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326816383&siteId=291194637