Google Guava--基础工具用法
Optional 优雅的解决Null(java 8 提供了Optional类)
Guava用Optional
Optional常用方法:
//创建指定引用的Optional实例,若引用为null则表示缺失
Optional<Shop> optional1 = Optional.fromNullable(null);
//创建指定引用的Optional实例,若引用为null则抛出NullPointerException
Optional<Shop> optional2 = Optional.of(new Shop(1,"name","addr","mobile",new Date()));
//optional1.isPresent() 如果Optional包含非null的引用(引用存在),返回true
System.out.println(optional1.isPresent()); //false
System.out.println(optional2.isPresent()); //true
//optional.or() //返回Optional所包含的引用,若引用缺失,返回指定的值
Shop shop=optional1.or(new Shop());
System.out.println(shop==null); //false
借助ComparisonChain 实现 Comparable 接口
如果我们不借助Guava,我们实现Comparable可能需要这样写:
@Override
public int compareTo(Shop that) {
int result = shop_id.compareTo(that.getShop_id();
if (result != 0) {
return result;
}
result = shop_name.compareTo(that.getShop_name());
return result;
}
当我们借助Guava ComparisonChain 实现 Comparable 接口我们可以这样写:
@Override
public int compareTo(Shop that) {
return ComparisonChain.start()
.compare(this.shop_id,that.getShop_id())
.compare(this.shop_name,that.getShop_name())
.result();
}
MoreObjects.toStringHelper() 帮助重写toString()方法
Shop newShop=new Shop(1,"帝都店","朝阳门","1111111",new Date());
System.out.println(newShop);
//demo.xxx.model.Shop@5babb90b
当类没有重写toString()方法时会调用object的toString()方法,代码如下:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
有时候为了方便调试我们可以使用 MoreObjects.toStringHelper() 帮助我们重写toString方法。
@Override
public String toString() {
return MoreObjects
.toStringHelper(this)
.add("shop_id", shop_id)
.add("shop_name",shop_name)
.add("create_time",create_time)
.toString();
}
//Shop{shop_id=1, shop_name=帝都店, create_time=Tue Jan 17 12:58:38 CST 2017}