Objects主要用来重写toString和HashCode方法。里面还有一个方法firstNonNull(T, T)返回两个值中不为null的一个如果都位null.抛出空指针
异常。
上代码看用法:
class="java" name="code">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);
}
}
看了一下 Objects.toStringHelper(this).omitNullValues().add("id", id).add("name", name).add("address", address).toString()这一段代码的源码记录一下:
Objects这一段代码采用链表的结构实现:
public static final class ToStringHelper {
private final String className;
private final ValueHolder holderHead = new ValueHolder();
private ValueHolder holderTail = holderHead;
private boolean omitNullValues = false;
定义了一个链表的头holderHead;
private ValueHolder addHolder() {
ValueHolder valueHolder = new ValueHolder();
holderTail = holderTail.next = valueHolder;
return valueHolder;
}
这一段代码指向下一个节点;
private ToStringHelper addHolder(String name, @Nullable Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
valueHolder.name = checkNotNull(name);
return this;
}
这一段代码首先调用addHolder指向下一个节点,然后给下一个节点赋值。