Guava是Google开源的,帮助程序员快速写出高质量代码的工具包,下面走马观花地看一下。
Collection
Guava使得我们创建集合类时更简单:
// 创建集合类
List<String> list = Lists.newArrayList();
List<Integer> list = Lists.newArrayList(1, 2, 3);
Map<String, Integer> list = Maps.newHashMap();
而且提供了一些不可变的集合类,比如:ImmutableList、ImmutableMap:
ImmutableMap<String, Integer> map = ImmutableMap.of(
"1", 1,
"2", 2,
"3", 3
);
ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder();
for (...) {
builder.put(name, age);
}
ImmutableMap<String, Integer> map = builder.build();
另外在Guava中也提供了一些集合工具类。
EventBus
相当于是对订阅者模式的简单封装,不需要我们再去做什么东西了,简单的用法如下,跟Future比较一下就知道它的好处了:
class MyEvent {
int value;
MyEvent(int value) {
this.value = value;
}
}
class MyEventListener {
@Subscribe
public void listen(MyEvent event) {
System.out.println(event.value); // 处理消息
}
}
public class Main {
public void static main() throws Exception {
EventBus eventBus = new EventBus("test");
eventBus.register(new MyEventListener()); // 注册监听者
eventBus.post(new MyEvent(200)); // 发布消息
}
}
在选择处理消息的方法时有两个依据:
- @Subscribe
- 参数类型是否和Event的类型匹配
如果event没有被listener消费,那么就会有一个DeadEvent放出来,这样可以监控到哪些消息是乱发的。
Cache
使用Guava可以实现一个本地缓存,简单的用法如下:
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build();
// 从缓存中获取数据
String resultVal = cache.get("jerry", new Callable<String>() {
public String call() {
String strProValue="hello "+"jerry"+"!";
return strProValue;
}
});
当然,可以设置超时时间等,感觉比较好的地方是可以在key被移除的时候得到通知:
Cache<String, String> cache = CacheBuilder.newBuilder().removalListener(new RemovalListener<K, V>(){
@Override
public void onRemoval(RemovalNotification<K, V> rn) {
System.out.println(rn.getKey()+"被移除");
}
}).build(cacheLoader);
ConCurrent
在并发方面,Guava提供的ListenableFuture更好用一点:
public class Test {
public static void main(String[] args) throws Exception {
// 创建线程池
ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1));
ExecutorService executorService = Executors.newFixedThreadPool(1);
// 创建异步的任务
final ListenableFuture<String> future = executor.submit(new Callable<String>() {
public String call() throws Exception {
Thread.sleep(1000);
return "Hello, ";
}
});
// 设置监听器A
future.addListener(new Runnable() {
public void run() {
try {
System.out.println(future.get() + "A");
} catch (InterruptedException e) {
future.cancel(true);
} catch (ExecutionException e) {
future.cancel(true);
}
}
}, executorService);
// 设置监听器B
future.addListener(new Runnable() {
public void run() {
try {
System.out.println(future.get() + "B");
} catch (InterruptedException e) {
future.cancel(true);
} catch (ExecutionException e) {
future.cancel(true);
}
}
}, executorService);
System.out.println("exit..");
}
}
reflect
在Guava中提供了一些工具,简化了反射的使用,比如获取泛型的类型时:
import java.lang.reflect.Type;
import com.google.common.reflect.TypeToken;
abstract class GetT<T> {
TypeToken<T> type = new TypeToken<T>(getClass()) {
};
}
public class Test<T> extends GetT<T> {
public static void main(String[] args) throws Exception {
Type t = new Test<String>() {
}.type.getType();
System.out.println(t);
}
}
关于泛型的其他东西可以看这里。
----------END----------