推荐2一个在Java编码过程中得心应手的工具

推荐2在编码过程中的减小不仅编码的量,挺easy工具上手:可适用Java反思与单探头Assert。

1 Mirror:Java反思

简单介绍

官网:http://projetos.vidageek.net/mirror/mirror/

将Java原生API提供的面向命令的语法:Class.getField/getDeclaredFields/getMethod()/getAnnotation之类的调用简化为DSL语法。訪问field/method/anntation的代码量大幅降低,更重要的是easy理解了,能够说是一眼看穿:
官网的样例,改动field的值,Java SDK的API编码:

//"target" is the object containing the field whose value you want to set. 
Field toSet = null;
for (Field f : target.getClass().getDeclaredFields()) { 
    //Get all fields DECLARED inside the target object class 
    if (f.getName().equals("field")) {
        toSet = f;
    }
}
if (toSet != null && (toSet.getModifiers() & Modifier.STATIC) == 0) {
    toSet.setAccessible(true);
    toSet.set(target, value);
}

基于Mirror的API

new Mirror().on(target).set().field(fieldName).withValue(value);

这样才干愉快的编码。!

特点

Mirror常规模式下提供:
* Field的读取、改动
* Method的读取、调用
* Constructor的读取、基于Constructor创建对象
* 标注于Class上的Annatation的读取

和cglib-nodep组合模式下能够创建Java Proxy,一句话搞定:

SomeClass proxy = new Mirror().proxify(SomeClass.class)
        .interceptingWith(new YourCustomMethodInterceptor());

2 AssertJ:更易用的单測Assert

在遇到AssertJ之前我用过JUnit和Hamcrest的Assert API,Hamcrest的接口强大可是那么不easy理解。

JUnit的API:麻绳提豆腐-别提了。

AssertJ支持对象指定Feild、方法返回值的断言,

// common assertions
assertThat(frodo.getName()).isEqualTo("Frodo");
assertThat(frodo).isNotEqualTo(sauron)
                 .isIn(fellowshipOfTheRing);

// String specific assertions
assertThat(frodo.getName()).startsWith("Fro")
                           .endsWith("do")
                           .isEqualToIgnoringCase("frodo");

并且对集合对象的遍历支持的很好:遍历的时候能够自己定义过滤条件filters

// collection specific assertions
List<TolkienCharacter> fellowshipOfTheRing = ...;
assertThat(fellowshipOfTheRing).hasSize(9)
                               .contains(frodo, sam)
                               .doesNotContain(sauron);

另一个有意思的Assert特性是continue on erros:soft-assertions

具体的使用说明见:joel-costigliola.github.io/assertj/assertj-core-features-highlight.html


引入maven依赖的时候,要注意JDK版本号:

<dependency>
  <groupId>org.assertj</groupId>
  <artifactId>assertj-core</artifactId>
  <!-- use 3.0.0 for Java 8 projects -->
  <!-- 2.0.0 required Java 7 -->
  <!-- 1.7.1 for Java 6 -->
  <version>1.7.1</version>
  <scope>test</scope>
</dependency>

高级版API提供Assert为Guava、Joda-Time、Neo4j、Swing的对象进行API级别推断。

版权声明:本文博主原创文章。博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/zfyouxi/p/4831968.html