public static
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
长话短说还是来个例子看看吧。
假如我们有一个TestBean ,其中包含一个Name属性,我们有的时候需要在使用这个Bean的时候判断一下他的值是否为空,怎么作呢?看下面的代码:
public class Test1
{
public static void main(String args[])
{
TestBean tbean=new TestBean();
Preconditions.checkNotNull(tbean.getName(),"Name can not be null");
}
}
这段代码会抛出类似下面的异常,告诉你这个Bean的name是不能为null的。
Exception in thread "main" java.lang.NullPointerException: Name can not be null
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:188)
at com.test.preconditions.Test1.main(Test1.java:11)
程序这是会中断。如果我们在Preconditions的方法之前加入一句:tbean.setName("Tomy").就不会出现这个异常了。
我们趁热打铁再来说另一个有用的方法,Preconditions.checkArgument()
这个方法接收一个boolean参数。如果参数为false的话就会抛出一个java.lang.IllegalArgumentException异常。举个例子,假如我们有一个名为Person的bean保存的人的信息,现在我们要判断他是否成年了(满18岁),为此我们在这个Bean中提供了一个isAdult方法,如果Person的age属性值不小于18岁就返回true否则返回false.按照传统的写法代码可能是这样的,
PersonBean pb=new PersonBean();
pb.setAge(18);
if(pb.isAdult){
throw new Exception("not adult!");
}
现在我们用google的Preconditions提供的方法,可以写成这样:
Preconditions.checkArgument(pb.isAdult,"not adult");
看看是不是简单了很多?
最后再介绍一个方法checkContentsNotNull()
他的参数是一个iterable接口,作用的校验参数内的集合是否为空或者是一个没有任何元素的空集合。
1 条评论:
MS加班也不是很忙嘛
发表评论