java 入参校验_java开发参入参数校验
一:字段少的校驗用法
Assert.notNull(payable, "Payable不能為空!");
Assert.notNull(payable.getNettingStatus(), "Payable.nettingStatus不能為空!");
一:字段多的校驗用法(自己寫了工具類)
/**
* 校驗對象屬性
*
* @author dy
* JDK-version: JDK1.7
* @since 2017.5.22
*/
public class ObjectUtils {
private static final Logger logger = LoggerFactory.getLogger(ObjectUtils.class);
/**
* 校驗對象屬性均不能為空!
*
* @param obj
* @return
* @author DengYang
*/
public static boolean validField(Object obj) throws IllegalAccessException {
if (obj == null)
throw new IllegalAccessException("參數不能為空!");
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
if (StringUtils.isEmpty(field.get(obj))) {
logger.error("==> " + field.getName() + "不能為空!");
throw new IllegalAccessException(field.getName() + "不能為空!");
}
}
return true;
}
/**
* 指定字段名字,校驗對象屬性不能為空!
*
* @param obj
* @return
* @author DengYang
*/
public static boolean validFieldByFileldName(Object obj, String... fieldName) throws IllegalAccessException {
if (obj == null)
throw new IllegalAccessException("參數不能為空!");
if (fieldName == null || fieldName.length < 1) {
throw new IllegalAccessException("fieldName參數不能為空!");
}
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
for (String name : fieldName) {
if (field.getName().equals(name)) {
if (StringUtils.isEmpty(field.get(obj))) {
logger.error("==> " + field.getName() + "不能為空!");
throw new IllegalAccessException(field.getName() + "不能為空!");
}
}
}
}
return true;
}
/**
* 過濾掉字段后,校驗剩余對象屬性不能為空!
*
* @param obj
* @return
* @author DengYang
*/
public static boolean validFieldWithFilter(Object obj, String... filterField) throws IllegalAccessException {
if (obj == null)
return false;
if (filterField == null || filterField.length < 1) {
throw new IllegalAccessException("fieldName參數不能為空!");
}
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
for (String filter : filterField) {
if (field.getName().equals(filter))
continue;
if (StringUtils.isEmpty(field.get(obj))) {
logger.error("==> " + field.getName() + "不能為空!");
throw new IllegalAccessException("fieldName參數不能為空!");
}
}
}
return true;
}
public static void main(String[] args) throws Exception {
Test user = new Test();
user.setName("阿斯蒂芬");
user.setAge(0);
// System.out.println(validField(user));
System.out.println(validFieldWithFilter(user, new String[]{"sdf", "沙發墊"}));
}
}
總結
以上是生活随笔為你收集整理的java 入参校验_java开发参入参数校验的全部內容,希望文章能夠幫你解決所遇到的問題。