性感的 Guava
What's Guava
Google 的一个开源项目,包含许多 Google 核心的 Java 常用库。
很多类似 Apache Common 的功能,但实现更优雅,项目也更活跃。
试图弥补 Java 语言的不足,很多特性被加入到最新的 Java 语言规范中。
Objects#equal
Objects.equal("a", "a"); // return true
Objects.equal(null, "a"); // return false
Objects.equal("a", null); // return false
Objects.equal(null, null); // return true
Java7 引入的 Objects 类提供了一样的方法 Objects.equals。
Objects#hashCode
public int hashCode() {
return Objects.hashCode(firstName, lastname, address);
}
Java7 引入的 Objects 类提供了一样的方法 Objects.hash(Object...)。
Objects#toString
public String toString() {
return Objects.toStringHelper(this)
.add("firstName", firstName)
.add("lastName", lastName)
.add("age", age)
.toString();
}
高版本的 Guava 里的 toStringHelper 方法移到了 MoreObjects 里了。
Comparable
public int compareTo(User that) {
return CComparisonChain.start()
.compare(this.firstName, that.firstName)
.compare(this.lastName, that.lastName)
.compare(this.age, that.age)
.compareFalseFirst(this.locked, that.locked)
.result();
}
PreConditions
//Preconditions.checkNotNull(arg1, "参数 arg1 不正确,不能为空。");
checkNotNull(arg1, "参数 arg1 不正确,不能为空。");
checkArgument(arg2 > 18, "参数 arg2 不正确,值是%s,必须大于18。", arg2);
| 方法声明 | 描述 | 检查失败时抛出的异常 |
|---|---|---|
| checkArgument(boolean) | 检查 boolean 是否为 true,用来检查传递给方法的参数。 | IllegalArgumentException |
| checkNotNull(T) | 检查 value 是否为 null,该方法直接返回 value,因此可以内嵌使用 checkNotNull。 | NullPointerException |
| checkState(boolean) | 用来检查对象的某些状态。 | IllegalStateException |
| checkElementIndex(int index, int size) | 列表、字符串或数组是否有效。index>=0 && index<size | IndexOutOfBoundsException |
| checkPositionIndex(int index, int size) | 检查index作为位置值对某个列表、字符串或数组是否有效。index>=0 && index<=size | IndexOutOfBoundsException |
| checkPositionIndexes(int start, int end, int size) | 检查\[start, end\]表示的位置范围对某个列表、字符串或数组是否有效 | IndexOutOfBoundsException |
Optional#or
String username = null;
// String name = username != null ? username ? "游客";
// String name = Objects.firstNonNull(username, "游客");
String name = Optional.of(username).or("游客");
System.out.println(name + "你好!"); // 游客你好!
相当于 JavaScript 中: var a = x || y;
Return null — What's mean?
This chapter requires login to view full content. You are viewing a preview.
Login to View Full Content