package com.vci.server.base.utility;
|
|
import java.beans.PropertyDescriptor;
|
import java.lang.reflect.Field;
|
|
import com.vci.common.annotaion.CustomAnnotaion;
|
|
public class LogHelper {
|
|
public LogHelper() {
|
}
|
|
public static String toNewLogString(Object obj) {
|
if (obj == null)
|
return "";
|
|
Class<?> objClass = obj.getClass();
|
|
Field[] fields = objClass.getDeclaredFields();
|
|
StringBuffer sbLog = new StringBuffer();
|
for(Field f : fields){
|
if(!f.isAnnotationPresent(CustomAnnotaion.class)){
|
continue;
|
}
|
|
CustomAnnotaion caField = f.getAnnotation(CustomAnnotaion.class);
|
if(caField.InToString()){
|
String fieldDes = caField.CustomDescription();
|
Object value = getTargetObjectValue(f, obj);
|
|
if (sbLog.length() > 0)
|
sbLog.append(", ");
|
|
sbLog.append(String.format("%s=%s", fieldDes, value));
|
}
|
}
|
|
return sbLog.toString();
|
}
|
|
public static String toUpdataLogString(Object oldObj, Object newObj) {
|
if (oldObj == null || newObj == null) {
|
//System.out.println("================================\n oldObj == null || newObj == null");
|
return "";
|
}
|
|
Class<?> objClass = newObj.getClass();
|
|
Field[] fields = objClass.getDeclaredFields();
|
|
StringBuffer sbBefor = new StringBuffer();
|
StringBuffer sbAfter = new StringBuffer();
|
for(Field f : fields){
|
if(!f.isAnnotationPresent(CustomAnnotaion.class)){
|
continue;
|
}
|
|
CustomAnnotaion caField = f.getAnnotation(CustomAnnotaion.class);
|
if(caField.InToString()){
|
String fieldDes = caField.CustomDescription();
|
String oldValue = getTargetObjectValue(f, oldObj);
|
String newValue = getTargetObjectValue(f, newObj);
|
//System.out.println(String.format("============== %s =======================\noldValue = %s; newValue = %s", fieldDes, oldValue, newValue));
|
|
if (oldValue.equals(newValue))
|
continue;
|
|
if (sbBefor.length() > 0)
|
sbBefor.append(", ");
|
sbBefor.append(String.format("%s=%s", fieldDes, oldValue));
|
|
if (sbAfter.length() > 0)
|
sbAfter.append(", ");
|
sbAfter.append(String.format("%s=%s", fieldDes, newValue));
|
}
|
}
|
|
if (sbAfter.length() == 0 || sbBefor.length() == 0) {
|
//System.out.println(String.format("=====================================\noldObj = %s; newObj = %s", sbBefor, sbAfter));
|
return "";
|
}
|
|
return String.format("更改前[%s];更改后[%s]", sbBefor.toString(), sbAfter.toString());
|
}
|
|
|
|
/**
|
* 通过内省机制获取字段值
|
* @param declaredField 字段
|
* @param t 对象
|
* @return 值
|
*/
|
private static String getTargetObjectValue(Field field, Object t) {
|
Object value;
|
try {
|
PropertyDescriptor propDesc = new PropertyDescriptor(field.getName(), t.getClass());
|
value = propDesc.getReadMethod().invoke(t);
|
|
if (value == null)
|
value = "";
|
} catch (Exception e) {
|
e.printStackTrace();
|
throw new RuntimeException("获取对应数据失败");
|
}
|
return value.toString();
|
}
|
|
}
|