反射递归显示具有属性类型,名称和值的对象

时间:2015-01-12 21:03:30

标签: java recursion reflection

我想要打印一些复杂的对象,包括属性名称,类型和值。只要我事先不知道所有属性/子属性的数量和深度,我就需要一个包含循环的递归调用。我已经完成了2个级别

StringBuilder descr = new StringBuilder();
foreach (PropertyInfo propertyInfo in req.GetType().GetProperties())
{
  if (propertyInfo.CanRead)
  {
    string attributValue = "";
    string attributName = propertyInfo.Name;
    Type attributType = propertyInfo.PropertyType;
    var propertyInfoValue = propertyInfo.GetValue(req, null);

    //if (attributType == typeof(XFkType))
    if (attributType != typeof(System.String) &&
        attributType != typeof(System.Boolean))
    {
        PropertyInfo[] nestedpropertyInfoArray = propertyInfo.PropertyType.GetProperties();
        attributValue += "{";
        foreach (PropertyInfo subProperty in nestedpropertyInfoArray)
        {
            // var instance = (EntityBase)Activator.CreateInstance(subClass);
            attributValue += subProperty.Name + "=";
            try
            {
                attributValue += propertyInfoValue == null ? "" : subProperty.GetValue(propertyInfoValue, null).ToString();
            }
            catch (Exception e)
            {
                attributValue += "null";
            }
            attributValue += ","; 

        }
        attributValue = attributValue.Length > 1 ? attributValue.Substring(0, attributValue.Length - 1) : attributValue;
        attributValue += "}";
    }
    else
        attributValue = propertyInfo.GetValue(req, null) == null ? "" : propertyInfo.GetValue(req, null).ToString();

    descr.Append("[" + propertyInfo.PropertyType + "]" + attributName + "=" + attributValue + " | ");
  }
}

结果如下:

  

[XPhone] class {Phone,protocol = SIP,protocolSide = User,callingSearchSpaceName = XFkType,devicePoolName = XFkType,commonDeviceConfigName = XFkType,commonPhoneConfigName = XFkType,networkLocation = Use System Default,locationName = XFkType,mediaResourceListName = null,wirelessLanProfileGroup = null,ctiid = null} | [System.UInt64] sequence = {} | [System.Boolean] sequenceSpecified = False |

1 个答案:

答案 0 :(得分:0)

理解你的结构有点困难,但我希望解决方案有以下形式:

public String propertyDescription(PropertyInfo[] properties) {
    StringBuilder description;
    for (PropertyInfo property: properties) {
        if (property.containsNestedProperties()) {
            description.append(propertyDescription(property.getNestedProperties()));
        } else {
            description.append( ... );
        }
    }
    return description.toString();
}