Java 反射递归显示具有属性类型、名称和值的对象
我想打印一些复杂的对象,包括属性名称、类型和值。只要我事先不知道所有属性/子属性的数量和深度,我就需要一个包含循环的递归调用。我已经做了两个级别Java 反射递归显示具有属性类型、名称和值的对象,java,recursion,reflection,Java,Recursion,Reflection,我想打印一些复杂的对象,包括属性名称、类型和值。只要我事先不知道所有属性/子属性的数量和深度,我就需要一个包含循环的递归调用。我已经做了两个级别 StringBuilder descr = new StringBuilder(); foreach (PropertyInfo propertyInfo in req.GetType().GetProperties()) { if (propertyInfo.CanRead) { string attributValue = "";
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]类{Phone,protocolSide=SIP,protocolSide=User,callingSearchSpaceName=XFkType,devicePoolName=XFkType,commonDeviceConfigName=XFkType,commonPhoneConfigName=XFkType,networkLocation=Use系统默认值,locationName=XFkType,mediaResourceListName=null,wirelessLanProfileGroup=null,CTID=null}}}}}}}}系统.UInt64]序列={}}}}}[System.Boolean]sequenceSpecified=假|
理解您的结构有点困难,但我希望解决方案如下所示:
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();
}
你的问题是什么?如何用提供的代码构建所需的递归循环。