1.工具类
package com.utils;
/**
* 类描述:前置条件检查
* 注意:对于运行时异常,java 不要求必须要处理,出现这样的异常,默认会由虚拟机接管
*
* @Author:ztd
* @date:2016年10月31日
* @Version:1.1.0
*/
public class PreConditions {
/**
* @param reference
* 给定的字符串
* @param errorMessage
* 错误提示信息
* @return 当前字符串
* @功能描述:检查给定的对象是不是为空
* @Author:ztd
* @date:2016年10月31日 下午2:50:57
* @Version:1.1.0
*/
public static <T> T checkNotNullAndThrowException(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* @param reference 被检查的对象
* @return
* @功能描述:检查对象是不是为空
* @Author:ztd
* @date:2016年10月31日 下午3:05:55
* @Version:1.1.0
*/
public static <T> boolean checkNotNull(T reference) {
boolean flag = true;
if (reference == null) {
flag = false;
}
return flag;
}
/**
* @param reference
* 被检查的字段
* @param errorMessage
* 错误提示信息
* @return 当前字段
* @功能描述:检查当前给定的字符串是不是空、空字符、null 字符串
* @Author:ztd
* @date:2016年10月31日 下午2:42:30
* @Version:1.1.0
*/
public static String checkNotEmptyAndThrowException(String reference) {
if (reference == null) {
throw new NullPointerException("对象为空.");
}
if (reference.equals("")) {
throw new NullPointerException("对象内容为\"\"字符串");
}
if (reference.equals("null")) {
throw new NullPointerException("对象内容为\"null\"字符串");
}
return reference;
}
/**
* @param reference
* 被检查的字段
* @return 检查结果
* @功能描述:检查当前给定的字符串是不是空、空字符、null 字符串
* @Author:ztd
* @date:2016年10月31日 下午2:42:30
* @Version:1.1.0
*/
public static Boolean checkNotEmpty(String reference) {
Boolean flag = true;
if (reference == null || reference.equals("") || reference.equals("null")) {
flag = false;
}
return flag;
}
/**
* @param reference 被检查的字符串
* @return 检查结果
* @功能描述:检查给定字符串是不是逻辑为空,并记录下字符串情况
* @Author:ztd
* @date:2016年10月31日 下午3:15:30
* @Version:1.1.0
*/
public static Boolean checkNotEmptyWithLog(String reference) {
Boolean flag = true;
if (reference == null) {
System.out.println("对象为空.");
return false;
}
if (reference.equals("")) {
System.out.println("对象内容为\"\"字符串");
return false;
}
if (reference.equals("null")) {
System.out.println("对象内容为\"null\"字符串");
return false;
}
return flag;
}
}
2.测试类
package com.utils;
public class PreConditionsTest {
public static void main(String[] args) {
String obj1 = null;
String obj2 = "";
// 检查对象是不是为空
System.out.println(PreConditions.checkNotNull(obj1));
System.out.println(PreConditions.checkNotNull(obj2));
String str1 = null;
String str2 = "";
String str3 = "null";
// 检查对象是不是为空
System.out.println(PreConditions.checkNotEmpty(str1));
System.out.println(PreConditions.checkNotEmpty(str2));
System.out.println(PreConditions.checkNotEmpty(str3));
// 检查对象是不是为空并记录下日志
System.out.println(PreConditions.checkNotEmptyWithLog(str1));
System.out.println(PreConditions.checkNotEmptyWithLog(str2));
System.out.println(PreConditions.checkNotEmptyWithLog(str3));
}
}
3.运行结果
false
true
false
false
false
对象为空.
false
对象内容为""字符串
false
对象内容为"null"字符串
false