標籤:工具 編碼 測試載入器 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 assertionsassertThat(frodo.getName()).isEqualTo("Frodo");assertThat(frodo).isNotEqualTo(sauron) .isIn(fellowshipOfTheRing);// String specific assertionsassertThat(frodo.getName()).startsWith("Fro") .endsWith("do") .isEqualToIgnoringCase("frodo");
而且對集合對象的遍曆支援的非常好:遍曆的時候可以自訂過濾條件filters。
// collection specific assertionsList<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層級判斷。
推薦2個在Java編碼過程好用的工具