javaBean非空校驗(借鑒的)



//校驗實體類非空判斷,精確到某個字段

import
lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author heyt * @date 2020/8/27 * */ @Slf4j public class BeanNotNullUtil { public static List<String> validateProperty(Object validateObj) { return validateProperty(validateObj,(String[])null); } /** * * @param cValidateObj 校驗的實體類 * @param cIgnoreProperties 排除不需要校驗的屬性 * @return */ public static List<String> validateProperty(Object cValidateObj, String... cIgnoreProperties) { PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(cValidateObj.getClass()); List<String> ignoreList = (cIgnoreProperties != null ? Arrays.asList(cIgnoreProperties) : null); List<String> errList = new ArrayList<>(); for (PropertyDescriptor targetPd : targetPds) { Method readMethod = targetPd.getReadMethod(); if (readMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) { try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(cValidateObj); if (value instanceof String) { if (StringUtils.isEmpty((String) value)) { errList.add(cValidateObj.getClass().getSimpleName()+ "." + targetPd.getName() + "不可為空"); continue; } } if (value == null) { errList.add(cValidateObj.getClass().getSimpleName() + "." + targetPd.getName() + "不可為空"); } } catch (Throwable ex) { log.info(ex.getMessage()); } } } return errList; } public static void main(String[] args) { // OrderInfoVO tOrderInfoVO = new OrderInfoVO(); // tOrderInfoVO.setOrderAmount("123123"); // tOrderInfoVO.setOrderNo("ijnuhygv"); // tOrderInfoVO.setShopNo("asdfedc"); //// String[] strs = {"insureTransaction","shopName","transactionType","transactionTime","transactionNo","transactionDetail"}; // String[] strs = {"transactionType","transactionTime","transactionDetail",""}; // // List<String> tLists = validateProperty(tOrderInfoVO,strs); // System.out.print(tLists.toString()); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM