通过apache的org.apache.commons.beanutils.BeanUtils(commons-beanutils-1.8.3.jar包下载)的BeanUtils.describe方法将对象的所有属性转换为字符串,如下代码所示分别打印对象、序列List及Map的字符串示例
import java.util.ArrayList;@b@import java.util.HashMap;@b@import java.util.List;@b@import java.util.Map;@b@import org.apache.commons.beanutils.BeanUtils;@b@@b@public class ObjectString {@b@ @b@ private String id;@b@ private String name;@b@ private String url;@b@ private String des;@b@ @b@ @b@ public ObjectString(String id, String name, String url, String des) {@b@ super();@b@ this.id = id;@b@ this.name = name;@b@ this.url = url;@b@ this.des = des;@b@ }@b@@b@@b@ public String getId() {@b@ return id;@b@ }@b@@b@@b@ public void setId(String id) {@b@ this.id = id;@b@ }@b@@b@@b@ public String getName() {@b@ return name;@b@ }@b@@b@@b@ public void setName(String name) {@b@ this.name = name;@b@ }@b@@b@@b@ public String getUrl() {@b@ return url;@b@ }@b@@b@@b@ public void setUrl(String url) {@b@ this.url = url;@b@ }@b@@b@@b@ public String getDes() {@b@ return des;@b@ }@b@@b@@b@ public void setDes(String des) {@b@ this.des = des;@b@ }@b@@b@ @b@ @Override@b@ public String toString() {@b@ try {@b@ return BeanUtils.describe(this).toString();@b@ } catch (Exception e) {@b@ }@b@ return "";@b@ }@b@@b@@b@ public static void main(String[] args) {@b@ @b@ ObjectString obja=new ObjectString("11","aa","aa11","1111111aaaaa");@b@ ObjectString objb=new ObjectString("22","bb","bb22","2222bbb");@b@ @b@ List<ObjectString> lists=new ArrayList<ObjectString>();@b@ lists.add(obja);@b@ lists.add(objb);@b@ @b@ Map<ObjectString,ObjectString> maps=new HashMap<ObjectString,ObjectString>();@b@ maps.put(obja, obja);@b@ maps.put(objb, objb);@b@ @b@ System.out.println("【obj String】:"+obja.toString());@b@ System.out.println("【list String】"+lists.toString());@b@ System.out.println("【map String】"+maps.toString());@b@@b@ }@b@ @b@@b@}
控制台输出结果如下
【obj String】:{id=11, des=1111111aaaaa, name=aa, class=class com.xwood.object.ObjectString, url=aa11}@b@【list String】[{id=11, des=1111111aaaaa, name=aa, class=class com.xwood.object.ObjectString, url=aa11}, {id=22, des=2222bbb, name=bb, class=class com.xwood.object.ObjectString, url=bb22}]@b@【map String】{{id=22, des=2222bbb, name=bb, class=class com.xwood.object.ObjectString, url=bb22}={id=22, des=2222bbb, name=bb, class=class com.xwood.object.ObjectString, url=bb22}, {id=11, des=1111111aaaaa, name=aa, class=class com.xwood.object.ObjectString, url=aa11}={id=11, des=1111111aaaaa, name=aa, class=class com.xwood.object.ObjectString, url=aa11}}