---
title: "Guava学习2"
author: "googi"
date: "2013-05-21T16:10:03Z"
tags: []
categories: ["编程语言"]
slug: "guava-2"
draft: false
lastmod: "2013-05-21T16:11:21Z"
id: 1872867
url: "https://googi.iteye.com/blog/1872867"
---

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 \[code="java"] 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 \[/code] 第二．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 一些代码例子： \[code="java"] 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 \[/code] 两大组成部分： 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相关处理： \[code="java"] List asList(prim... backingArray) prim\[] toArray(Collection 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) \[/code] 通过的util方法： \[code="java"] int compare(prim a, prim b) prim checkedCast(long value) prim saturatedCast(long value) \[/code] 字节转换方法： \[code="java"] int BYTES prim fromByteArray(byte\[] bytes) prim fromBytes(byte b1, ..., byte bk) byte\[] toByteArray(prim value) \[/code] 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) 实例代码： \[code="java"] 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 \[/code] Range关联： encloses关系： \[code="java"] 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 \[/code] 可否相连关系isConnected： \[code="java"] 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 \[/code] 映射关系intersection： \[code="java"] 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 \[/code] 跨度范围span: \[code="java"] 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] \[/code] PART7. Reflection 第一． 取泛型信息：TypeToken JDK通过反射可以获取泛型信息，主要通过ParameterizedType，而TypeToken就是基于这个特性进行的封装。使用： Note that if mapToken just returned new TypeToken&gt;(), it could not actually reify the types assigned to K and V, so for example: \[code="java"] class Util { static TypeToken&gt; incorrectMapToken() { return new TypeToken&gt;() {}; } } System.out.println(Util.incorrectMapToken()); // just prints out "java.util.Map" 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 { TypeToken type = new TypeToken(getClass()) {}; } ... new IKnowMyType() {}.type; // returns a correct TypeToken \[/code] 第二． Invokable,这是对java.lang.reflect.Method and java.lang.reflect.Constructor封装后的类。 创建： Invokable invoke = Invokable.from(Method method) Invokable invoke = Invokable.from(Constructor constructor) 使用： 判断方法是否public: JDK: Modifier.isPublic(method.getModifiers()) Invokable: invokable.isPublic() 判断方法是否可以由子类覆盖： JDK: \[code="java"] !(Modifier.isFinal(method.getModifiers()) || Modifiers.isPrivate(method.getModifiers()) || Modifiers.isStatic(method.getModifiers()) || Modifiers.isFinal(method.getDeclaringClass().getModifiers())) \[/code] Invokable: \[code="java"] invokable.isOverridable() \[/code] 判断方法的第一个参数是否是由@Nullable annotated: JDK: \[code="java"] for (Annotation annotation : method.getParameterAnnotations\[0]) { if (annotation instanceof Nullable) { return true; } } return false; \[/code] Invokable: \[code="java"] invokable.getParameters().get(0).isAnnotationPresent(Nullable.class) invokable.invoke(object, args); \[/code] 第三． 动态代理 JDK: \[code="java"] Foo foo = (Foo) Proxy.newProxyInstance( Foo.class.getClassLoader(), new Class\[] {Foo.class}, invocationHandler); \[/code] Guava: \[code="java"] Foo foo = Reflection.newProxy(Foo.class, invocationHandler); \[/code]