PART3. Concurrency
加了个ListenableFuture接口:
[code]
ListenableFuture extends Future{
void addListener(Runnable paramRunnable, Executor paramExecutor);
}
[/code]
代码实例:
[code]
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
ListenableFuture explosion = service.submit(new Callable() {
public Explosion call() {
return pushBigRedButton();
}
});
Futures.addCallback(explosion, new FutureCallback() {
// we want this handler to run immediately after we push the big red button!
public void onSuccess(Explosion explosion) {
walkAwayFrom(explosion);
}
public void onFailure(Throwable thrown) {
battleArchNemesis(); // escaped the explosion!
}
});
[/code]
PART4. String
第一. Joiner
第二.Splitter
In JAVA, ",a,,b,".split(",") result : ["", "a", "", "b"] 默认忽略最后的空字符串,但前面的不省略,行为有点奇怪。
而Guava中:
Splitter.on(','). split(" a,,b ")
result : [“ a”,””,”b ”]
Splitter.on(',').trimResults().split(" a,,b ")
result : [“a”,””,”b”]
Splitter.on(',').trimResults().omitEmptyStrings().split(",a,,b,")
result : [“a”,”b”]
System.out.println(Splitter.on(',').limit(3).split("a,b,c,d,e"));
//["a","b","c,d,e"]
第三.CharMatcher
一些代码例子:
两大组成部分:
CharMatcher有一下几种:allAscii collapse collapseControlChars collapseWhitespace indexOfChars
lastIndexNotOf numSharedChars removeChars removeCrLf replaceChars
retainAllChars strip stripAndCollapse stripNonDigits
处理机制:
collapseFrom(CharSequence, char):Replace each group of consecutive matched characters with the specified character. For example, WHITESPACE.collapseFrom(string, ' ') collapses whitespaces down to a single space.
matchesAllOf(CharSequence):Test if this matcher matches all characters in the sequence. For example, ASCII.matchesAllOf(string) tests if all characters in the string are ASCII.
removeFrom(CharSequence):Removes matching characters from the sequence.
retainFrom(CharSequence):Removes all non-matching characters from the sequence.
trimFrom(CharSequence):Removes leading and trailing matching characters.
replaceFrom(CharSequence, CharSequence):Replace matching characters with a given sequence.
第四.CharSets
PART5. Primitives
Utilities for primitives: Bytes,Shorts,Ints,Longs,Floats,Doubles,Chars,Booleans
这些原始类的util类里主要有一下几类功能:
Array相关处理:
通过的util方法:
字节转换方法:
PART6. Ranges(基于JAVA实现,在动态语言如Groovy中更简便)
创建:
(a..b) open(C, C)
[a..b] closed(C, C)
[a..b) closedOpen(C, C)
(a..b] openClosed(C, C)
(a..+∞) greaterThan(C)
[a..+∞) atLeast(C)
(-∞..b) lessThan(C)
(-∞..b] atMost(C)
(-∞..+∞) all()
以上的方式也可以通过加入BoundType(OPEN,CLOSED两种)的方式获得:
Bounded on both ends range(C, BoundType, C, BoundType)
Unbounded on top ((a..+∞) or [a..+∞)) downTo(C, BoundType)
Unbounded on bottom ((-∞..b) or (-∞..b]) upTo(C, BoundType)
实例代码:
Range关联:
encloses关系:
可否相连关系isConnected:
映射关系intersection:
跨度范围span:
PART7. Reflection
第一. 取泛型信息:TypeToken
JDK通过反射可以获取泛型信息,主要通过ParameterizedType,而TypeToken就是基于这个特性进行的封装。使用:
Note that if mapToken just returned new TypeToken<Map<K, V>>(), it could not actually reify the types assigned to K and V, so for example:
第二. Invokable,这是对java.lang.reflect.Method and java.lang.reflect.Constructor封装后的类。
创建:
Invokable invoke = Invokable.from(Method method)
Invokable invoke = Invokable.from(Constructor<T> constructor)
使用:
判断方法是否public:
JDK: Modifier.isPublic(method.getModifiers())
Invokable: invokable.isPublic()
判断方法是否可以由子类覆盖:
JDK:
Invokable:
判断方法的第一个参数是否是由@Nullable annotated:
JDK:
Invokable:
第三. 动态代理
JDK:
Guava:
加了个ListenableFuture接口:
[code]
ListenableFuture extends Future{
void addListener(Runnable paramRunnable, Executor paramExecutor);
}
[/code]
代码实例:
[code]
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
ListenableFuture explosion = service.submit(new Callable() {
public Explosion call() {
return pushBigRedButton();
}
});
Futures.addCallback(explosion, new FutureCallback() {
// we want this handler to run immediately after we push the big red button!
public void onSuccess(Explosion explosion) {
walkAwayFrom(explosion);
}
public void onFailure(Throwable thrown) {
battleArchNemesis(); // escaped the explosion!
}
});
[/code]
PART4. String
第一. Joiner
Joiner joiner = Joiner.on("; ").skipNulls();
System.out.println(joiner.join("Harry", null, "Ron", "Hermione"));
// Harry; Ron; Hermione
Joiner joiner2 = Joiner.on("; ").useForNull("yaya");
System.out.println(joiner2.join("Harry", null, "Ron", "Hermione"));
// Harry; yaya; Ron; Hermione
Joiner joiner3 = Joiner.on("; ").useForNull(null);
System.out.println(joiner3.join("Harry", null, "Ron", "Hermione"));
// throw NullPointException
Joiner joiner4 = Joiner.on("; ").useForNull(null);
System.out.println(joiner4.join("Harry", null, "Ron", "Hermione"));
// throw NullPointException
第二.Splitter
In JAVA, ",a,,b,".split(",") result : ["", "a", "", "b"] 默认忽略最后的空字符串,但前面的不省略,行为有点奇怪。
而Guava中:
Splitter.on(','). split(" a,,b ")
result : [“ a”,””,”b ”]
Splitter.on(',').trimResults().split(" a,,b ")
result : [“a”,””,”b”]
Splitter.on(',').trimResults().omitEmptyStrings().split(",a,,b,")
result : [“a”,”b”]
System.out.println(Splitter.on(',').limit(3).split("a,b,c,d,e"));
//["a","b","c,d,e"]
第三.CharMatcher
一些代码例子:
String noControl = CharMatcher.JAVA_ISO_CONTROL.removeFrom(string); // remove control characters
String theDigits = CharMatcher.DIGIT.retainFrom(string); // only the digits
String spaced = CharMatcher.WHITESPACE.trimAndCollapseFrom(string, ' ');
// trim whitespace at ends, and replace/collapse whitespace into single spaces
String noDigits = CharMatcher.JAVA_DIGIT.replaceFrom(string, "*"); // star out all digits
String lowerAndDigit = CharMatcher.JAVA_DIGIT.or(CharMatcher.JAVA_LOWER_CASE).retainFrom(string);
// eliminate all characters that aren't digits or lowercase
两大组成部分:
CharMatcher有一下几种:allAscii collapse collapseControlChars collapseWhitespace indexOfChars
lastIndexNotOf numSharedChars removeChars removeCrLf replaceChars
retainAllChars strip stripAndCollapse stripNonDigits
处理机制:
collapseFrom(CharSequence, char):Replace each group of consecutive matched characters with the specified character. For example, WHITESPACE.collapseFrom(string, ' ') collapses whitespaces down to a single space.
matchesAllOf(CharSequence):Test if this matcher matches all characters in the sequence. For example, ASCII.matchesAllOf(string) tests if all characters in the string are ASCII.
removeFrom(CharSequence):Removes matching characters from the sequence.
retainFrom(CharSequence):Removes all non-matching characters from the sequence.
trimFrom(CharSequence):Removes leading and trailing matching characters.
replaceFrom(CharSequence, CharSequence):Replace matching characters with a given sequence.
第四.CharSets
PART5. Primitives
Utilities for primitives: Bytes,Shorts,Ints,Longs,Floats,Doubles,Chars,Booleans
这些原始类的util类里主要有一下几类功能:
Array相关处理:
List<Wrapper> asList(prim... backingArray)
prim[] toArray(Collection<Wrapper> collection)
prim[] concat(prim[]... arrays)
boolean contains(prim[] array, prim target)
int indexOf(prim[] array, prim target)
int lastIndexOf(prim[] array, prim target)
prim min(prim... array)
prim max(prim... array)
String join(String separator, prim... array)
通过的util方法:
int compare(prim a, prim b)
prim checkedCast(long value)
prim saturatedCast(long value)
字节转换方法:
int BYTES
prim fromByteArray(byte[] bytes)
prim fromBytes(byte b1, ..., byte bk)
byte[] toByteArray(prim value)
PART6. Ranges(基于JAVA实现,在动态语言如Groovy中更简便)
创建:
(a..b) open(C, C)
[a..b] closed(C, C)
[a..b) closedOpen(C, C)
(a..b] openClosed(C, C)
(a..+∞) greaterThan(C)
[a..+∞) atLeast(C)
(-∞..b) lessThan(C)
(-∞..b] atMost(C)
(-∞..+∞) all()
以上的方式也可以通过加入BoundType(OPEN,CLOSED两种)的方式获得:
Bounded on both ends range(C, BoundType, C, BoundType)
Unbounded on top ((a..+∞) or [a..+∞)) downTo(C, BoundType)
Unbounded on bottom ((-∞..b) or (-∞..b]) upTo(C, BoundType)
实例代码:
Range.closed(1, 3).contains(2); // returns true
Range.closed(1, 3).contains(4); // returns false
Range.lessThan(5).contains(5); // returns false
Range.closed(1, 4).containsAll(Ints.asList(1, 2, 3)); // returns true
Range.closedOpen(4, 4).isEmpty(); // returns true
Range.openClosed(4, 4).isEmpty(); // returns true
Range.closed(4, 4).isEmpty(); // returns false
Range.open(4, 4).isEmpty(); // Range.open throws IllegalArgumentException
Range.closed(3, 10).lowerEndpoint(); // returns 3
Range.open(3, 10).lowerEndpoint(); // returns 3
Range.closed(3, 10).lowerBoundType(); // returns CLOSED
Range.open(3, 10).upperBoundType(); // returns OPEN
Range关联:
encloses关系:
Range r1 = Range.open(11, 19);
Range r2 = Range.open(2, 14);
System.out.println(r1.encloses(r2)); //false
Range r3 = Range.open(12, 14);
System.out.println(r1.encloses(r3)); //true
Range r4 = Range.closedOpen(4, 4);
System.out.println(r4.isEmpty()); //true
System.out.println(r1.encloses(r4)); //false
Range r5 = Range.closedOpen(14, 14);
System.out.println(r5.isEmpty()); //true
System.out.println(r1.encloses(r5)); //true
可否相连关系isConnected:
Range.closed(3, 5).isConnected(Range.open(5, 10)); // returns true
Range.closed(0, 9).isConnected(Range.closed(3, 4)); // returns true
Range.closed(0, 5).isConnected(Range.closed(3, 9)); // returns true
Range.open(3, 5).isConnected(Range.open(5, 10)); // returns false
Range.closed(1, 5).isConnected(Range.closed(6, 10)); // returns false
映射关系intersection:
Range.closed(3, 5).intersection(Range.open(5, 10)); // returns (5, 5]
Range.closed(0, 9).intersection(Range.closed(3, 4)); // returns [3, 4]
Range.closed(0, 5).intersection(Range.closed(3, 9)); // returns [3, 5]
Range.open(3, 5).intersection(Range.open(5, 10)); // throws IAE
Range.closed(1, 5).intersection(Range.closed(6, 10)); // throws IAE
跨度范围span:
Range.closed(3, 5).span(Range.open(5, 10)); // returns [3, 10)
Range.closed(0, 9).span(Range.closed(3, 4)); // returns [0, 9]
Range.closed(0, 5).span(Range.closed(3, 9)); // returns [0, 9]
Range.open(3, 5).span(Range.open(5, 10)); // returns (3, 10)
Range.closed(1, 5).span(Range.closed(6, 10)); // returns [1, 10]
PART7. Reflection
第一. 取泛型信息:TypeToken
JDK通过反射可以获取泛型信息,主要通过ParameterizedType,而TypeToken就是基于这个特性进行的封装。使用:
Note that if mapToken just returned new TypeToken<Map<K, V>>(), it could not actually reify the types assigned to K and V, so for example:
class Util {
static <K, V> TypeToken<Map<K, V>> incorrectMapToken() {
return new TypeToken<Map<K, V>>() {};
}
}
System.out.println(Util.<String, BigInteger>incorrectMapToken());
// just prints out "java.util.Map<K, V>"
Alternately, you can capture a generic type with a (usually anonymous) subclass and resolve it against a context class that knows what the type parameters are.
abstract class IKnowMyType<T> {
TypeToken<T> type = new TypeToken<T>(getClass()) {};
}
...
new IKnowMyType<String>() {}.type; // returns a correct TypeToken<String>
第二. Invokable,这是对java.lang.reflect.Method and java.lang.reflect.Constructor封装后的类。
创建:
Invokable invoke = Invokable.from(Method method)
Invokable invoke = Invokable.from(Constructor<T> constructor)
使用:
判断方法是否public:
JDK: Modifier.isPublic(method.getModifiers())
Invokable: invokable.isPublic()
判断方法是否可以由子类覆盖:
JDK:
!(Modifier.isFinal(method.getModifiers())
|| Modifiers.isPrivate(method.getModifiers())
|| Modifiers.isStatic(method.getModifiers())
|| Modifiers.isFinal(method.getDeclaringClass().getModifiers()))
Invokable:
invokable.isOverridable()
判断方法的第一个参数是否是由@Nullable annotated:
JDK:
for (Annotation annotation : method.getParameterAnnotations[0]) {
if (annotation instanceof Nullable) {
return true;
}
}
return false;
Invokable:
invokable.getParameters().get(0).isAnnotationPresent(Nullable.class)
invokable.invoke(object, args);
第三. 动态代理
JDK:
Foo foo = (Foo) Proxy.newProxyInstance(
Foo.class.getClassLoader(),
new Class<?>[] {Foo.class},
invocationHandler);
Guava:
Foo foo = Reflection.newProxy(Foo.class, invocationHandler);