1 Preconditions
Preconditions.checkArgument(true);//判断是否为true.否则抛出IllegalArgumentException
Preconditions.checkNotNull(1);//NullPointerException
Preconditions.checkState(true);//老实说,这个与 checkArgument 源代码一致..只是老外为了区分参数还是状态值吧
//还有一些检查数组越界的方法.就不介绍了.个人感觉用处不大.
具体看一下下图就明白了
这个怎么说呢,感觉用处不大..特别是在Guava在同事中并没有大批量推行的时候,如果我这边写这么一条check.抛了一个Exception,,对其他同事排查问题可能会有障碍.因为他在review这个代码的时候没注意到这个有可能抛异常..我宁可写一个显式的抛异常代码来替代这个.
2 Objects
提供了equals,hashCode与toString方法.前面的两个,个人觉得就那样,非常推荐最后的toString非常推荐,特别是在打日志的时候..具体如下
public class ObjectsDemo {
public static void main(String[] args) throws Exception{
Objects.equal("a", "a"); // returns true
Objects.equal(null, "a"); // returns false
Objects.equal("a", null); // returns false
Objects.equal(null, null); // returns true
ObjectsDemo od = new ObjectsDemo();
od.query(0l,null);
}
public Object query(Long userId,Long itemId){
if(itemId == null || userId == null){
throw new IllegalArgumentException(Objects.toStringHelper("query error.").add("userId", userId).add("itemId", itemId).toString());
}
// do query
return null;
}
}
最后的输出是
写道
Exception in thread "main" java.lang.IllegalArgumentException: query error.{userId=0, itemId=null}
还是很优雅的
3 Throwables
JDK7已经支持的非常好了.不多说了..没有意义