推荐2个在Java编码过程好用的工具

推荐2个在编码过程中既能减少编码量,又非常容易上手的工具类:适用于Java反射和单测Assert。

1 Mirror:Java反射

简介

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

将Java原生API提供的面向命令的语法:Class.getField/getDeclaredFields/getMethod()/getAnnotation之类的调用简化为DSL语法,访问field/method/anntation的代码量大幅减少,更重要的是容易理解了,可以说是一眼看穿:
官网的例子,修改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的接口强大但是那么不容易理解。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级别判断。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值