package com.vci.common.annotaion;
|
|
import java.lang.reflect.Field;
|
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.Method;
|
|
public class CustomAnnotaionHelper{
|
/**
|
* 返回对象 toString() 方法的输出内容
|
* @param obj 对象
|
* @param sb 包含内容的StringBuffer对象,该对象将作为引用参数传入
|
*/
|
public void getToString(Object obj, StringBuffer sb){
|
if(obj == null) {
|
return;
|
}
|
Class<?> objClazz = obj.getClass();
|
Field[] fields = objClazz.getDeclaredFields();
|
CustomAnnotaion caClazz = objClazz.getAnnotation(CustomAnnotaion.class);
|
String objName = obj.getClass().getSimpleName();
|
if(caClazz != null){
|
objName = caClazz.CustomDescription();
|
}
|
StringBuffer sbFields = new StringBuffer();
|
for(Field f : fields){
|
if(f.getName().equals("serialVersionUID")){
|
continue;
|
}
|
String fieldName = getCustomeDescription(objClazz, f.getName());
|
Object fieldValue = getFieldValue(objClazz, obj, f.getName());
|
if(f.isAnnotationPresent(CustomAnnotaion.class)){
|
CustomAnnotaion caField = f.getAnnotation(CustomAnnotaion.class);
|
if(caField.InToString()){
|
sbFields.append(String.format("%s=%s,", fieldName, fieldValue));
|
}
|
}
|
}
|
if(sbFields.length() != 0){
|
sbFields.replace(sbFields.length() - 1, sbFields.length(), "");
|
}
|
sb.append(String.format("%s [%s]", objName, sbFields.toString()));
|
}
|
public String getCustomeDescription(Class<?> objClazz, String fieldName){
|
String res = fieldName;
|
Field f;
|
try {
|
f = objClazz.getDeclaredField(fieldName);
|
if(f != null){
|
CustomAnnotaion an = f.getAnnotation(CustomAnnotaion.class);
|
if(an != null){
|
res = an.CustomDescription();
|
}
|
}
|
} catch (SecurityException e) {
|
e.printStackTrace();
|
} catch (NoSuchFieldException e) {
|
e.printStackTrace();
|
}
|
return res;
|
}
|
private Object getFieldValue(Class<?> objClazz, Object obj, String fieldName){
|
Object res = "";
|
String method = getMethodName(fieldName);
|
try {
|
Method m = objClazz.getMethod(method);
|
if(m != null){
|
res = m.invoke(obj);
|
}
|
} catch (SecurityException e) {
|
e.printStackTrace();
|
} catch (NoSuchMethodException e) {
|
e.printStackTrace();
|
} catch (IllegalArgumentException e) {
|
e.printStackTrace();
|
} catch (IllegalAccessException e) {
|
e.printStackTrace();
|
} catch (InvocationTargetException e) {
|
e.printStackTrace();
|
}
|
return res;
|
}
|
private String getMethodName(String fieldName){
|
return "get" + String.valueOf(fieldName.charAt(0)).toUpperCase() + fieldName.substring(1);
|
}
|
}
|