packagecom.pmo.util;importjava.lang.reflect.Field;importjava.lang.reflect.Method;importjava.math.BigDecimal;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.Date;importjava.util.List;/*** Created by ASUS on 2019/9/9.
* 反射工具类*/
public classReflectTool {privateReflectTool(){};/*** 获取字段对应值,并转为String类型,空值返回空字符串
*@paramfieldName
*@paramobj
*@return
*/
public static synchronized String getStringValue(String fieldName,Object obj) throwsReflectiveOperationException{
Object objectValue=getValueByGetter(fieldName,obj);if (objectValue == null){return "";
}
String result=objectValue.toString();//如果类型为BigDecimal,去掉末尾的0
if (objectValue instanceofBigDecimal){
BigDecimal value=(BigDecimal) objectValue;
value=value.stripTrailingZeros();
result=value.toPlainString();
}else if (objectValue instanceofDate){
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result= sdf.format((Date)objectValue).replace(" 00:00:00", "");
}returnresult.trim();
}public static Object getValueByGetter (String fieldName,Object obj) throwsReflectiveOperationException {
Method getter=getGetter(fieldName, obj.getClass());if (getter != null){returngetter.invoke(obj);
}return null;
}public static Object setValueBySetter (String fieldName,Object obj) throwsReflectiveOperationException {
Method setter=getSetter(fieldName, obj.getClass());if (setter == null){throw new ReflectiveOperationException("没有set方法");
}returnsetter.invoke(obj);
}/*** 获取get方法
*@paramfieldName
*@paramcls
*@return
*/
public static Method getGetter(String fieldName,Class>cls){for(Method method : cls.getMethods()) {if (method.getName().equalsIgnoreCase("get".concat(fieldName)) && method.getParameterTypes().length == 0){returnmethod;
}
}return null;
}/*** 获取set方法
*@paramfieldName
*@paramcls
*@return
*/
public static Method getSetter(String fieldName,Class>cls){for(Method method : cls.getMethods()) {if (method.getName().equalsIgnoreCase("set".concat(fieldName)) && method.getParameterTypes().length == 0){returnmethod;
}
}return null;
}/*** 通过属性名获取Field对象
*@paramfieldName
*@paramcls
*@return
*/
public static synchronized Field getFieldByName(String fieldName,Class>cls){
Field[] fields=cls.getDeclaredFields();for(Field field : fields){if(field.getName().equals(fieldName)){returnfield;
}
}if (cls.getSuperclass() != null){returngetFieldByName(fieldName,cls.getSuperclass());
}return null;
}/*** 通过对象.class获取所有Fields,包括父类
*@paramcls
*@return
*/
public static List listFields(Class>cls){
Field[] fs=cls.getDeclaredFields();
List fields = new ArrayList<>(Arrays.asList(fs));if (cls.getSuperclass() !=null){
fields.addAll(listFields(cls.getSuperclass()));
}returnfields;
}public static boolean fieldExist(String fieldName,Class>cls){return getFieldByName(fieldName, cls) !=null;
}
}