guava是Java的一个扩展类库
guava是Java的一个扩展类库,在google的许多项目中使用过了,现在最为一个 开源的Java类库广泛使用(http://code.google.com/p/guava-libraries/)。
guava类库扩展的主要是这些相关类:collections(集合类),concurrency(并发),primitives,reflection(反射),comparison,I/O,hashing,networking(网络),strings(字符串),math(计算),in-memory caching(内存缓存),in-memory publish/subscirbe(内存发布订阅)等。
guava的目标是让我们写更少的代码,并且可以让我们写的代码更简单、清晰、可读性强。
下面我们对guava的使用方法和场景做一些介绍。
guava库需要在大于JDK1.6的版本下使用。
1.预先判断Preconditions
通常我们检查参数,是用如下方法
public void setRating(Double rating){
if(rating == null){
throw new NullPointerException();
}
Double r = rating;
}
如果你使用guava的类库,可以使代码更加简洁
public void setRating(Double rating){ Double r = checkNotNull(rating); }
不过,记得添加静态引用(import static com.google.common.base.Preconditions.checkNotNull;),在Eclipse中的设置,可以参考(eclipse中添加静态引用)
除了checkNotNull之外,Preconditions还提供了一些其他的方法,如chekArgument,checkState,checkElementIndex,checkPositionIndex等,更多可参考Preconditions API。
2.Object.toStringHelper()
这个方法主要是用于更加简单的实现Object.toString()方法