2017 年最流行、最好用的 Java 库

原文地址:

http://mp.weixin.qq.com/s?__biz=MzI1OTIyNzY3Mw==&mid=2247483753&idx=1&sn=2f9b1aa8f29436e6d2d1dabb1066d3f7&chksm=ea7d681fdd0ae109ff6cb218ab13700fd3764fd385fc692a6ca8418d687bb59fe9d292303517&mpshare=1&scene=23&srcid=0224J82AJOyRvpBg9HLPvckX#rd

文章介绍

这篇文章介绍了2017 年最流行、最好用的 Java 库,从事 Java 或 Android 开发的同学不要错过了。

正文

Guice

Guice (发音同 juice) 是 Google 开发的一款适用于 Java 6+ 的依赖注入框架。

# 依赖注入方式public class DatabaseTransactionLogProvider implements Provider<TransactionLog> {  @Inject Connection connection;  public TransactionLog get() {    return new DatabaseTransactionLog(connection);
  }
}
# FactoryModuleBuilder generates factory using your interfacepublic interface PaymentFactory {   Payment create(Date startDate, Money amount);
}
GitHub:https://github.com/google/guice
JavaDoc: https://google.github.io/guice/api-docs/latest/javadoc/index.html
网址:https://github.com/google/guice/wiki/Motivation
FactoryModuleBuilder:https://google.github.io/guice/api-docs/latest/javadoc/index.html

OkHttp

OkHttp 是目前非常流行的网络请求框架。高效地执行 Http 请求能够让你的数据加载更快、带宽消耗更少。

OkHttp 的高效率来自以下几个特性:

支持 HTTP/2;这允许所有对相同 host 的请求共用一个 socket;
如果还没有升级到 HTTP/2,OkHttp 内部的请求池也能减少你的请求延时;
GZIP 能压缩数据下载体积;
对 Response 进行自动 cache 可以加快重复请求的响应速度
OkHttpClient client = new OkHttpClient();String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();  return response.body().string();
}
GitHub:https://github.com/square/okhttp
网址:http://square.github.io/okhttp/

Retrofit

这是一款 Square 公司开发的针对 Android 和 Java 的类型安全 Http Client。Retrofit 可以把你的 Http API 转化为 Java 接口。

public interface GitHubService {    @GET("users/{user}/repos")
    Call<List<Repo>listRepos(@Path("user") String user);
}
此处 Retrofit 会生成一个 GitHubService 的接口。

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);
利用这个接口,我们可以向远程服务器直接执行同步或异步的 Http Request。

Call<List<Repo>> repos = service.listRepos("octocat");
GitHub:https://github.com/square/retrofit
网址:http://square.github.io/retrofit/

JDeferred

这是一款类似 JQuery 的 Java Deferred/Promise 库,具备如下特性:

Deferred object and Promise
Promise 回调: .then(…), .done(…), .fail(…), .progress(…), .always(…)
Multiple promises: .when(p1, p2, p3, …).then(…)
Callable 和 Runnable: wrappers.when(new Runnable() {…})
使用 Executor Service
Java 范型支持: Deferred, deferred.resolve(10);, deferred.reject(new Exception());,deferred.notify(0.80);,
Android支持
Java 8 Lambda 友好

GitHub:https://github.com/jdeferred/jdeferred

网址:http://jdeferred.org/

RxJava

RxJava – JVM 的响应式扩展 – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.

它在观察者模式的基础上进行了扩展,支持 data/events 的序列化,增加了多种操作符来组装数据序列,而且,你完全不用关心底层的线程切换、同步机制、线程安全及并发数据结构。

RxJava 最广为人知的一种用法是:在后台线程执行高密度计算工作、网络请求等,然后回到 UI 主线程来显示执行结果。

 Flowable.fromCallable(() -{
     Thread.sleep(1000); //  imitate expensive computation
     return "Done";
 })
   .subscribeOn(Schedulers.io())
   .observeOn(Schedulers.single())
   .subscribe(System.out::println, Throwable::printStackTrace);

 Thread.sleep(2000); // <--- wait for the flow to finish
GitHub:https://github.com/ReactiveX/RxJava
Wiki:https://github.com/ReactiveX/RxJava/wiki

MBassador

MBassador 是一款基于发布-订阅模式的轻量级、高性能的事件总线。它使用起来非常简便,功能丰富,而且可以自扩展来进一步提高性能、减少资源开销。

MBassador 高性能的最关键原因在于一种特殊的数据结构,这种数据结构可最大限度减小锁竞争。

基于注解
同步/异步事件发布
可配置引用类型
事件过滤
事件包裹
Handler优先级
自定义错误处理
扩展性
// Define your listener
class SimpleFileListener{
    [@Handler](https://my.oschina.net/u/994780)
    public void handle(File msg){
      // do something with the file
    }
}

// somewhere else in your code
MBassador bus = new MBassador();
Object listener = new SimpleFileListener();
bus.subscribe (listener);
bus.post(new File("/tmp/smallfile.csv")).now();
bus.post(new File("/tmp/bigfile.csv")).asynchronously();
网址:https://github.com/bennidi/mbassador
Javadoc:http://bennidi.github.io/mbassador/

Project Lombok

使用注解 annotation 来减少代码重复,例如 getter、setter、not null检查、生成 Builder 等。下面有一些 Project Lombok 的 feature:

val - 自动解析变量的返回类型,并且该变量是 final 类,如 final String foo = example.get(0); var foo = example.get(0);
[@NonNull](https://my.oschina.net/u/2981441) - 自动 check 非空并抛异常;
@Cleanup - 自动关闭资源,调用 close() 方法;
@Getter / @Setter - 不用再写 public int getFoo() {return foo;} 了;
@ToString - 不用再开启 Debugger 来看某个值了,它能自动生成一个 toString 方法;
@EqualsAndHashCode - 更方便地比较两个对象是否相等;
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor - 自动按顺序生成构造函数;
@Data - 同时包括 @ToString, @EqualsAndHashCode, @Getter 对所有变量, @Setter 对所有非 final 变量, @RequiredArgsConstructor

GitHub:https://github.com/rzwitserloot/lombok

网址:https://projectlombok.org/

Simple Logging Facade for Java (SLF4J)

The Simple Logging Facade for Java (SLF4J) 是一个日志库抽象层,并非真正的日志库,可以支持不同的日志实现,如java.util.logging, logback, log4j。开发者可以利用这个抽象层来随时切换底层日志实现框架。

实际上,SLF4J所提供的核心API是一些接口以及一个LoggerFactory的工厂类。在使用SLF4J的时候,不需要在代码中或配置文件中指定你打算使用那个具体的日志系统。SLF4J提供了统一的记录日志的接口,只要按照其提供的方法记录即可,最终日志的格式、记录级别、输出方式等通过具体日志系统的配置来实现,因此可以在应用中灵活切换日志系统。

那么什么时候使用SLF4J比较合适呢?

如果你开发的是类库或者嵌入式组件,那么就应该考虑采用SLF4J,因为不可能影响最终用户选择哪种日志系统。在另一方面,如果是一个简单或者独立的应用,确定只有一种日志系统,那么就没有使用SLF4J的必要。假设你打算将你使用log4j的产品卖给要求使用JDK 1.4 Logging的用户时,面对成千上万的log4j调用的修改,相信这绝对不是一件轻松的事情。但是如果开始便使用SLF4J,那么这种转换将是非常轻松的事情。

网址:http://www.slf4j.org/
GitHub:https://github.com/qos-ch/slf4j
FAQ:https://www.slf4j.org/faq.html

JUnitParams

@Test
@Parameters({"17, false", 
             "22, true" })
public void personIsAdult(int age, boolean valid) throws Exception {
    assertThat(new Person(age).isAdult(), is(valid));
}
它的优势如下:

更加明显 - 参数直接放在 test method 里,而非 class 里
更加简洁 - 不需要构造函数来设置参数
参数可以通过 csv String 或 parameters provider class 来提供

网址:http://pragmatists.github.io/JUnitParams

GitHub:https://github.com/Pragmatists/JUnitParams
Quickstart:https://github.com/Pragmatists/junitparams/wiki/Quickstart
Mockito

Tasty mocking framework for unit tests in Java

 //You can mock concrete classes, not just interfaces
 LinkedList mockedList = mock(LinkedList.class);

 //stubbing
 when(mockedList.get(0)).thenReturn("first");
 when(mockedList.get(1)).thenThrow(new RuntimeException());

 //following prints "first"
 System.out.println(mockedList.get(0));

 //following throws runtime exception
 System.out.println(mockedList.get(1));

 //following prints "null" because get(999) was not stubbed
 System.out.println(mockedList.get(999));

 //Although it is possible to verify a stubbed invocation, usually it's just redundant
 //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
 //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See here.
 verify(mockedList).get(0);
网址:http://site.mockito.org/
GitHub:https://github.com/mockito/mockito
文档:http://static.javadoc.io/org.mockito/mockito-core/2.7.9/org/mockito/Mockito.html)

猜你喜欢

转载自my.oschina.net/u/2385255/blog/845550
今日推荐