引數校驗反射工具包
阿新 • • 發佈:2019-01-05
/** * 反射工具包 * * @author */ public final class BeanRefUtil { /** 隱藏構造器 */ private BeanRefUtil() { } /** * set屬性的值到Bean * * @param bean * @param valMap */ public static void setFieldValue(Object bean, Map<String, String> valMap) { Class<?> cls = bean.getClass(); // 取出bean裡的所有方法 Method[] methods = cls.getDeclaredMethods(); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { try { String fieldSetName = parSetName(field.getName()); if (!checkSetMet(methods, fieldSetName)) { continue; } Method fieldSetMet = cls.getMethod(fieldSetName, field.getType()); // String fieldKeyName = parKeyName(field.getName()); String fieldKeyName = field.getName(); String value = valMap.get(fieldKeyName); if (null != value && !"".equals(value)) { String fieldType = field.getType().getSimpleName(); if ("String".equals(fieldType)) { fieldSetMet.invoke(bean, value); } else if ("Date".equals(fieldType)) { Date temp = parseDate(value); fieldSetMet.invoke(bean, temp); } else if ("Integer".equals(fieldType) || "int".equals(fieldType)) { Integer intval = Integer.parseInt(value); fieldSetMet.invoke(bean, intval); } else if ("Long".equalsIgnoreCase(fieldType)) { Long temp = Long.parseLong(value); fieldSetMet.invoke(bean, temp); } else if ("Double".equalsIgnoreCase(fieldType)) { Double temp = Double.parseDouble(value); fieldSetMet.invoke(bean, temp); } else if ("Boolean".equalsIgnoreCase(fieldType)) { Boolean temp = Boolean.parseBoolean(value); fieldSetMet.invoke(bean, temp); } else { System.out.println("not supper type" + fieldType); } } } catch (Exception e) { continue; } } } /** * 取Bean的屬性和值對應關係的MAP * * @param bean * @return Map */ public static Map<String, String> getFieldValueMap(Object bean) { Class<?> cls = bean.getClass(); Map<String, String> valueMap = new HashMap<String, String>(); Method[] methods = cls.getDeclaredMethods(); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { try { String fieldType = field.getType().getSimpleName(); String fieldGetName = parGetName(field.getName()); if (!checkGetMet(methods, fieldGetName)) { continue; } Method fieldGetMet = cls.getMethod(fieldGetName, new Class[] {}); Object fieldVal = fieldGetMet.invoke(bean, new Object[] {}); String result = null; if ("Date".equals(fieldType)) { result = fmtDate((Date) fieldVal); } else { if (null != fieldVal) { result = String.valueOf(fieldVal); } } // String fieldKeyName = parKeyName(field.getName()); valueMap.put(field.getName(), result); } catch (Exception e) { continue; } } return valueMap; } /** * 格式化string為Date * * @param datestr * @return date */ public static Date parseDate(String datestr) { if (null == datestr || "".equals(datestr)) { return null; } try { String fmtstr = null; if (datestr.indexOf(':') > 0) { fmtstr = "yyyy-MM-dd HH:mm:ss"; } else { fmtstr = "yyyy-MM-dd"; } SimpleDateFormat sdf = new SimpleDateFormat(fmtstr, Locale.UK); return sdf.parse(datestr); } catch (Exception e) { return null; } } /** * 日期轉化為String * * @param date * @return date string */ public static String fmtDate(Date date) { if (null == date) { return null; } try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); return sdf.format(date); } catch (Exception e) { return null; } } /** * 判斷是否存在某屬性的 set方法 * * @param methods * @param fieldSetMet * @return boolean */ public static boolean checkSetMet(Method[] methods, String fieldSetMet) { for (Method met : methods) { if (fieldSetMet.equals(met.getName())) { return true; } } return false; } /** * 判斷是否存在某屬性的 get方法 * * @param methods * @param fieldGetMet * @return boolean */ public static boolean checkGetMet(Method[] methods, String fieldGetMet) { for (Method met : methods) { if (fieldGetMet.equals(met.getName())) { return true; } } return false; } /** * 拼接某屬性的 get方法 * * @param fieldName * @return String */ public static String parGetName(String fieldName) { if (null == fieldName || "".equals(fieldName)) { return null; } int startIndex = 0; if (fieldName.charAt(0) == '_') { startIndex = 1; } return "get" + fieldName.substring(startIndex, startIndex + 1).toUpperCase() + fieldName.substring(startIndex + 1); } /** * 拼接在某屬性的 set方法 * * @param fieldName * @return String */ public static String parSetName(String fieldName) { if (null == fieldName || "".equals(fieldName)) { return null; } int startIndex = 0; if (fieldName.charAt(0) == '_') { startIndex = 1; } return "set" + fieldName.substring(startIndex, startIndex + 1).toUpperCase() + fieldName.substring(startIndex + 1); } /** * 驗證引數是否合法 * * @return true:驗證通過 false:驗證失敗 * @throws SecurityException 安全 * @throws IllegalArgumentException 非法引數 * @throws NoSuchMethodException 沒有找到方法 * @throws IllegalAccessException 訪問欄位許可權 * @throws InvocationTargetException 呼叫異常 */ public static boolean validateFiled(ValidateFiled[] valiedatefiles, Object[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { for (ValidateFiled validateFiled : valiedatefiles) { Object arg = null; if ("".equals(validateFiled.filedName())) { arg = args[validateFiled.index()]; } else { arg = getFieldByObjectAndFileName(args[validateFiled.index()], validateFiled.filedName()); } // 判斷引數是否為空 if (validateFiled.notNull()) { if (arg == null) { return false; } } else { // 如果該引數能夠為空,並且當引數為空時,就不用判斷後面的了 ,直接返回true if (arg == null) { return true; } } if (validateFiled.maxLen() > 0) { // 判斷字串最大長度 if (((String) arg).length() > validateFiled.maxLen()) { return false; } } if (validateFiled.minLen() > 0) { // 判斷字串最小長度 if (((String) arg).length() < validateFiled.minLen()) { return false; } } if (validateFiled.maxVal() != -1) { // 判斷數值最大值 if ((Integer) arg > validateFiled.maxVal()) { return false; } } if (validateFiled.minVal() != -1) { // 判斷數值最小值 if ((Integer) arg < validateFiled.minVal()) { return false; } } if (!"".equals(validateFiled.regStr())) { // 判斷正則 if (arg instanceof String) { if (!((String) arg).matches(validateFiled.regStr())) { return false; } } else { return false; } } } return true; } /** * 根據物件和屬性名得到 屬性 * @throws SecurityException 安全 * @throws IllegalArgumentException 非法引數 * @throws NoSuchMethodException 沒有找到方法 * @throws IllegalAccessException 訪問欄位許可權 * @throws InvocationTargetException 呼叫異常 * @return 獲取對應object的對應屬性 */ public static Object getFieldByObjectAndFileName(Object targetObj, String fileName) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { String[] tmp = fileName.split("\\."); Object arg = targetObj; for (int i = 0; i < tmp.length; i++) { Method methdo = arg.getClass().getMethod(getGetterNameByFiledName(tmp[i])); arg = methdo.invoke(arg); } return arg; } /** * 根據屬性名 得到該屬性的getter方法名 * @return 對應欄位的get方法名 */ public static String getGetterNameByFiledName(String fieldName) { return "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); } /** * 根據目標方法和註解型別 得到該目標方法的指定註解 * @return 根據類獲取其註解 */ public static Annotation getAnnotationByMethod(Method method, Class annoClass) { Annotation[] all = method.getAnnotations(); for (Annotation annotation : all) { if (annotation.annotationType() == annoClass) { return annotation; } } return null; } /** * 根據類和方法名得到方法 * @return 根據類 獲取其方法名列表 */ public static Method getMethodByClassAndName(Class c, String methodName) { Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { return method; } } return null; } }