提交 11ba795f 编写于 作者: C Calvin

#21 整理基础类的使用并更新文档, 防御式编程校验参数的Validate类

上级 3e76c076
......@@ -2,10 +2,14 @@ package org.springside.examples.showcase.utilities.validate;
import static org.junit.Assert.*;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.Lists;
/**
* 演示用Apache Commons3的Validate,在代码中进行防御性校验.
*
......@@ -17,7 +21,7 @@ public class ValidateDemo {
@Test
public void asserts() {
//not null
//not null Object
try {
String parameter = "abc";
......@@ -25,31 +29,43 @@ public class ValidateDemo {
String result = Validate.notNull(parameter);
assertEquals("abc", result);
//检验not null,用默认出错信息.
Validate.notNull(null);
Assert.fail();
} catch (NullPointerException e) {
assertEquals("The validated object is null", e.getMessage());
}
//notBlank blank
//notBlank String
try {
String parameter = "abc";
String result = Validate.notBlank(parameter);
assertEquals("abc", result);
Validate.notBlank("");
//检验not null,用自定义出错信息.
Validate.notBlank("", "The name must not be blank");
Assert.fail();
} catch (IllegalArgumentException e) {
assertEquals("The name must not be blank", e.getMessage());
}
//notEmpty Collection
try {
List parameter = Lists.newArrayList();
List result = Validate.notEmpty(parameter);
Assert.fail();
} catch (IllegalArgumentException e) {
assertEquals("The validated collection is empty", e.getMessage());
}
//is true
try {
Validate.isTrue(false);
//出錯信息可格式化參數
Validate.isTrue(1 == 3, "Message %s", "foo");
Assert.fail();
} catch (IllegalArgumentException e) {
assertEquals("Message foo", e.getMessage());
}
}
}
......@@ -10,7 +10,7 @@
<property name="mailSender" ref="mailSender" />
<property name="textTemplate">
<value><![CDATA[
用戶%1$s在%2$tF被修改.
用戶%s在%tF被修改.
System Administrator.
]]></value>
</property>
......
......@@ -122,11 +122,13 @@ public class Collections3 {
return null;
}
//当类型为List时,直接取得最后一个元素 。
if (collection instanceof List) {
List<T> list = (List<T>) collection;
return list.get(list.size() - 1);
}
//其他类型通过iterator滚动到最后一个元素.
Iterator<T> iterator = collection.iterator();
while (true) {
T current = iterator.next();
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册