该工具类主要用于处理特定类型的属性的默认值,如默认Double类型属性为空时赋值为0的工具类
Java代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| package com.spi.utils;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
@Slf4j public class ObjectFiledsUtil {
public static Object objectDoubleTypeFiledDeal(Object object) throws NoSuchMethodException { Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { if (field.getType().getName().equals("java.lang.Double")){ field.setAccessible(true); String key = field.getName(); String method = key.substring(0,1).toUpperCase()+key.substring(1);
Method getMethod = object.getClass().getMethod("get"+method); Object value = null; try { value = getMethod.invoke(object); } catch (IllegalAccessException e) { log.error("IllegalAccessException Error Info {}", e.getMessage(), e); } catch (InvocationTargetException e) { log.error("InvocationTargetException Error Info {}", e.getMessage(), e); }
if (NullOrEmpty(value)){ Method setMethod = object.getClass().getMethod("set" + method, Double.class); try { setMethod.invoke(object, 0.0); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
} return object; }
public static boolean NullOrEmpty(Object value){ if (value == null || "".equals(value)) { return true; } else { return false; } }
}
|