最近有个需求,需要将不同对象中同一个字段做同一的处理,但是他可能是某个对象的属性,也可能是对象属性的属性。。。。这样嵌套下去。
这种需求,首先想到使用反射,然后算法上使用递归。
来上代码:
public void manCountryCode(Object businessData, Integer operationType)
{
busLogger.enterFuncDebugLog(businessData);
if (null == businessData)
{
busLogger.exitFuncDebugLog();
return;
}
try
{
manCountryCodeByOperationType(businessData, operationType);
}
catch (Throwable e)
{
busLogger.excepFuncDebugLog(e);
}
busLogger.exitFuncDebugLog(businessData);
}
private void manCountryCodeByOperationType(Object businessData,
Integer operationType) throws Exception
{
busLogger.enterFuncDebugLog(businessData);
if (recurseDepth == 0)
{
recurseDepth = 100;
return;
}
recurseDepth--;
for (Method method : businessData.getClass().getMethods())
{
//不是getter方法或者没有找到setter方法,则跳过该字段
if (!isGetter(method)
|| null == findSetterByGetter(businessData, method))
{
continue;
}
Class fieldType = method.getReturnType();
if (isSimpleFieldType(fieldType))
{
if (isSubNoField(method))
{
manSubNoCountryCode(businessData, method, operationType);
}
}
else if (isCollectionType(fieldType))
{
Object returnCollection = method.invoke(businessData);
processCollectionField(returnCollection, operationType);
}
else if (Map.class.isAssignableFrom(fieldType))
{
Map mapField = (Map) method.invoke(businessData);
for (Object value : mapField.values())
{
manCountryCode(value, operationType);
}
}
else
{
processComplexField(businessData, method, operationType);
}
}
busLogger.exitFuncDebugLog();
}
private void processCollectionField(Object returnCollection,
Integer operationType) throws Exception
{
busLogger.enterFuncDebugLog();
if (null != returnCollection)
{
for (Object element : (Collection) returnCollection)
{
if (!isSimpleFieldType(element.getClass()))
{
manCountryCode(element, operationType);
}
}
}
busLogger.exitFuncDebugLog();
}
private void processComplexField(Object businessData, Method method,
Integer operationType) throws Exception
{
busLogger.enterFuncDebugLog();
Object field = method.invoke(businessData);
if (null != field && isCollectionType(field.getClass()))
{
for (Object element : (Collection) field)
{
if (!isSimpleFieldType(element.getClass()))
{
manCountryCode(element, operationType);
}
}
}
else
{
manCountryCode(field, operationType);
}
busLogger.exitFuncDebugLog(field);
}
private boolean isCollectionType(Class fieldType)
{
return Collection.class.isAssignableFrom(fieldType);
}