Guava项目包括了多个Google的核心库,包括collections、caching、primitives 、concurrency libraries、common annotations、string processing、I/O等,他们被广泛用于Google项目的开发。
学习地址:[url]http://code.google.com/p/guava-libraries/wiki/GuavaExplained?tm=6[/url]
[b][size=x-lOptional:通过它避免使用null,或说避免null的歧义性[/size][/b]
避免用null,null是造成BUG的罪魁祸首,举个例子,通过Map#get(key),返回是null,既有可以是没有该键,也有可能是键对应的值是null,这种似是而非的情况容易造成程序Bug。
为解决这个问题,Guava引入了一个Optional:
来看一个Optional的使用:
如果possible不赋值,则isPresent()为false,否则为true,这样就避免了进行 == null的判断。
Optional可以是任何的对象的封装对象,有了它,你就可以避免使用 ==null的判断了。
它有3个静态方法:
|Optional.of(T) | Make an Optional containing the given non-null value, or fail fast on null.|
|Optional.absent() | Return an absent Optional of some type.|
|Optional.fromNullable(T) |Turn the given possibly-null reference into an Optional, treating non-null as present and null as absent.|
另外还有几个非表态方法:
[table]
|boolean isPresent() |Returns true if this Optional contains a non-null instance.|
|T get() |Returns the contained T instance, which must be present; otherwise, throws an IllegalStateException.|
|T or(T) | Returns the present value in this Optional, or if there is none, returns the specified default.|
|T orNull() | Returns the present value in this Optional, or if there is none, returns null. The inverse operation of fromNullable.|
|Set<T> asSet() |Returns an immutable singleton Set containing the instance in this Optional, if there is one, or otherwise an empty immutable set.|
[/table]
[b][size=x-large]Preconditions:一般用于方法入参校验[/size][/b]
入参预校验,保证方法入参的合法性,及时抛出异常。相当于Spring 的Assert.notNull,Assert.notEmpty的功用,如:
[b][size=x-large]用于排序的比较器[/size][/b]
[b][size=large]Ordering[/size][/b]
比较器类,可以很方便地扩展之:
[b]构造Ordering实现[/b]
拥有多个静态方法,方便构造出Ordering实例,如:
[table]
|natural() | Uses the natural ordering on Comparable types.|
|usingToString() | Compares Objects by the lexicographical ordering of their string representations, as returned by toString().|
|arbitrary() |Returns an arbitrary ordering over all objects, for which compare(a, b) == 0 implies a == b (identity equality). There is no meaning whatsoever to the order imposed, but it is constant for the life of the VM.|
[/table]
[b]对Ordering进行控制[/b]
[table]
|reverse() | Returns the reverse ordering.|
|nullsFirst() |Returns an Ordering that orders nulls before non-null elements, and otherwise behaves the same as the original Ordering. See also nullsLast().|
|compound(Comparator) |Returns an Ordering which uses the specified Comparator to "break ties."|
|lexicographical() |Returns an Ordering that orders iterables lexicographically by their elements.|
|onResultOf(Function) |Returns an Ordering which orders values by applying the function to them and then comparing the results using the original Ordering.|
[/table]
nullsFirst()方法显式指定对null这位怪人才要如何处理,对应的有nullsLast()
假设我们希望按sortedBy字段进行排序:
下面的这个排序可以处理可能含有null的sortedBy问题:
[b]对Ordering常用方法[/b]
[table]
|Method| Description| See also|
|greatestOf(Iterable iterable, int k)| Returns the k greatest elements of the specified iterable, according to this ordering, in order from greatest to least. Not necessarily stable.|leastOf|
|isOrdered(Iterable)| Tests if the specified Iterable is in nondecreasing order according to this ordering.|isStrictlyOrdered|
|sortedCopy(Iterable)| Returns a sorted copy of the specified elements as a List.|immutableSortedCopy|
|min(E, E)| Returns the minimum of its two arguments according to this ordering. If the values compare as equal, the first argument is returned.|max(E, E)|
|min(E, E, E, E...)| Returns the minimum of its arguments according to this ordering. If there are multiple least values, the first is returned.|max(E, E, E, E...)|
|min(Iterable)| Returns the minimum element of the specified Iterable. Throws a NoSuchElementException if the Iterable is empty.|max(Iterable), min(Iterator), max(Iterator)|
[/table]
[b][size=x-large] Object通用方法的处理 [/size][/b]
Object定义了若干通用的方法,包括equals,toString等,子类要实现它们往往比较烦人(简单是简单,但大量重复性劳动)
[b][size=large]equals[/size][/b]
面对null不再需要特殊处理了:
[b][size=large] hashCode[/size][/b]
想基于哪些字段产生hashCode,直接指定就可以了。
[b][size=large] toString[/size][/b]
类似地:
[b][size=large] compare/compareTo[/size][/b]
考虑下面的这段“原始”代码:
使用ComparisonChain进行排序:
注意anEnum是一个数组或List ,都可以了。
[b][size=x-large]处理异常[/size][/b]
在tye/catch中处理一些异常,传播另一些异常:
[table]
|Signature| Explanation|
|RuntimeException propagate(Throwable)| Propagates the throwable as-is if it is a RuntimeException or an Error, or wraps it in a RuntimeException and throws it otherwise. Guaranteed to throw. The return type is a RuntimeException so you can write throw Throwables.propagate(t) as above, and Java will realize that that line is guaranteed to throw an exception.|
|void propagateIfInstanceOf(Throwable, Class<X extends Exception>) throws X| Propagates the throwable as-is, if and only if it is an instance of X.|
|void propagateIfPossible(Throwable)| Throws throwable as-is only if it is a RuntimeException or an Error.|
|void propagateIfPossible(Throwable, Class<X extends Throwable>) throws X| Throws throwable as-is only if it is a RuntimeException, an Error, or an X.
[/table]
通过如下方法获取异常迹:
学习地址:[url]http://code.google.com/p/guava-libraries/wiki/GuavaExplained?tm=6[/url]
[b][size=x-lOptional:通过它避免使用null,或说避免null的歧义性[/size][/b]
避免用null,null是造成BUG的罪魁祸首,举个例子,通过Map#get(key),返回是null,既有可以是没有该键,也有可能是键对应的值是null,这种似是而非的情况容易造成程序Bug。
为解决这个问题,Guava引入了一个Optional:
来看一个Optional的使用:
Optional<Integer> possible = Optional.of(5);//创建一个整数Optional对象
possible.isPresent(); // returns true
possible.get(); // returns 5
如果possible不赋值,则isPresent()为false,否则为true,这样就避免了进行 == null的判断。
Optional可以是任何的对象的封装对象,有了它,你就可以避免使用 ==null的判断了。
它有3个静态方法:
|Optional.of(T) | Make an Optional containing the given non-null value, or fail fast on null.|
|Optional.absent() | Return an absent Optional of some type.|
|Optional.fromNullable(T) |Turn the given possibly-null reference into an Optional, treating non-null as present and null as absent.|
另外还有几个非表态方法:
[table]
|boolean isPresent() |Returns true if this Optional contains a non-null instance.|
|T get() |Returns the contained T instance, which must be present; otherwise, throws an IllegalStateException.|
|T or(T) | Returns the present value in this Optional, or if there is none, returns the specified default.|
|T orNull() | Returns the present value in this Optional, or if there is none, returns null. The inverse operation of fromNullable.|
|Set<T> asSet() |Returns an immutable singleton Set containing the instance in this Optional, if there is one, or otherwise an empty immutable set.|
[/table]
[b][size=x-large]Preconditions:一般用于方法入参校验[/size][/b]
入参预校验,保证方法入参的合法性,及时抛出异常。相当于Spring 的Assert.notNull,Assert.notEmpty的功用,如:
checkArgument(i >= 0, "Argument was %s but expected nonnegative", i);
checkArgument(i < j, "Expected i < j, but %s > %s", i, j);
[b][size=x-large]用于排序的比较器[/size][/b]
[b][size=large]Ordering[/size][/b]
比较器类,可以很方便地扩展之:
Ordering<String> byLengthOrdering = new Ordering<String>() {
public int compare(String left, String right) {
return Ints.compare(left.length(), right.length());
}
};
if (Ordering.from(comparator).reverse().isOrdered(list)) { ... }
[b]构造Ordering实现[/b]
拥有多个静态方法,方便构造出Ordering实例,如:
[table]
|natural() | Uses the natural ordering on Comparable types.|
|usingToString() | Compares Objects by the lexicographical ordering of their string representations, as returned by toString().|
|arbitrary() |Returns an arbitrary ordering over all objects, for which compare(a, b) == 0 implies a == b (identity equality). There is no meaning whatsoever to the order imposed, but it is constant for the life of the VM.|
[/table]
[b]对Ordering进行控制[/b]
[table]
|reverse() | Returns the reverse ordering.|
|nullsFirst() |Returns an Ordering that orders nulls before non-null elements, and otherwise behaves the same as the original Ordering. See also nullsLast().|
|compound(Comparator) |Returns an Ordering which uses the specified Comparator to "break ties."|
|lexicographical() |Returns an Ordering that orders iterables lexicographically by their elements.|
|onResultOf(Function) |Returns an Ordering which orders values by applying the function to them and then comparing the results using the original Ordering.|
[/table]
nullsFirst()方法显式指定对null这位怪人才要如何处理,对应的有nullsLast()
假设我们希望按sortedBy字段进行排序:
class Foo {
@Nullable String sortedBy;
int notSortedBy;
}
下面的这个排序可以处理可能含有null的sortedBy问题:
Ordering<Foo> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<Foo, String>() {
public String apply(Foo foo) {
return foo.sortedBy;
}
});
[b]对Ordering常用方法[/b]
[table]
|Method| Description| See also|
|greatestOf(Iterable iterable, int k)| Returns the k greatest elements of the specified iterable, according to this ordering, in order from greatest to least. Not necessarily stable.|leastOf|
|isOrdered(Iterable)| Tests if the specified Iterable is in nondecreasing order according to this ordering.|isStrictlyOrdered|
|sortedCopy(Iterable)| Returns a sorted copy of the specified elements as a List.|immutableSortedCopy|
|min(E, E)| Returns the minimum of its two arguments according to this ordering. If the values compare as equal, the first argument is returned.|max(E, E)|
|min(E, E, E, E...)| Returns the minimum of its arguments according to this ordering. If there are multiple least values, the first is returned.|max(E, E, E, E...)|
|min(Iterable)| Returns the minimum element of the specified Iterable. Throws a NoSuchElementException if the Iterable is empty.|max(Iterable), min(Iterator), max(Iterator)|
[/table]
[b][size=x-large] Object通用方法的处理 [/size][/b]
Object定义了若干通用的方法,包括equals,toString等,子类要实现它们往往比较烦人(简单是简单,但大量重复性劳动)
[b][size=large]equals[/size][/b]
面对null不再需要特殊处理了:
Objects.equal("a", "a"); // returns true
Objects.equal(null, "a"); // returns false
Objects.equal("a", null); // returns false
Objects.equal(null, null); // returns true
[b][size=large] hashCode[/size][/b]
Objects.hashCode(field1, field2, ..., fieldn)
想基于哪些字段产生hashCode,直接指定就可以了。
[b][size=large] toString[/size][/b]
类似地:
Objects.toStringHelper(this)
.add("x", 1)
.toString();
// Returns "MyObject{x=1}"
Objects.toStringHelper("MyObject")
.add("x", 1)
.toString();
[b][size=large] compare/compareTo[/size][/b]
考虑下面的这段“原始”代码:
class Person implements Comparable<Person> {
private String lastName;
private String firstName;
private int zipCode;
public int compareTo(Person other) {
int cmp = lastName.compareTo(other.lastName);
if (cmp != 0) {
return cmp;
}
cmp = firstName.compareTo(other.firstName);
if (cmp != 0) {
return cmp;
}
return Integer.compare(zipCode, other.zipCode);
}
}
使用ComparisonChain进行排序:
public int compareTo(Foo that) {
return ComparisonChain.start()
.compare(this.aString, that.aString)
.compare(this.anInt, that.anInt)
.compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
.result();
}
注意anEnum是一个数组或List ,都可以了。
[b][size=x-large]处理异常[/size][/b]
在tye/catch中处理一些异常,传播另一些异常:
try {
someMethodThatCouldThrowAnything();
} catch (IKnowWhatToDoWithThisException e) {
handle(e);
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, IOException.class);
Throwables.propagateIfInstanceOf(t, SQLException.class);
throw Throwables.propagate(t);
}
[table]
|Signature| Explanation|
|RuntimeException propagate(Throwable)| Propagates the throwable as-is if it is a RuntimeException or an Error, or wraps it in a RuntimeException and throws it otherwise. Guaranteed to throw. The return type is a RuntimeException so you can write throw Throwables.propagate(t) as above, and Java will realize that that line is guaranteed to throw an exception.|
|void propagateIfInstanceOf(Throwable, Class<X extends Exception>) throws X| Propagates the throwable as-is, if and only if it is an instance of X.|
|void propagateIfPossible(Throwable)| Throws throwable as-is only if it is a RuntimeException or an Error.|
|void propagateIfPossible(Throwable, Class<X extends Throwable>) throws X| Throws throwable as-is only if it is a RuntimeException, an Error, or an X.
[/table]
通过如下方法获取异常迹:
Throwable getRootCause(Throwable)
List<Throwable> getCausalChain(Throwable)
String getStackTraceAsString(Throwable)