欢迎来到天天文库
浏览记录
ID:47549750
大小:70.85 KB
页数:10页
时间:2020-01-14
《使用Iterator模式将对象转成String》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、操纵JSOM、XML、Javabean等对象时你可能最先想到访问者模式。但是使用访问者模式很难从调用代码控制回调。比如,不能有条件的从所有回调的子分支和叶子节点跳过某个分支。解决这个问题就可以使用Iterator模式遍历整个对象,生成易于开发者阅读和调试的字符串。该迭代器具备一定的通用性,我在使用XPath查找Java对象和在StackHunter中记录异常的工具中都用到了它。API本文主要介绍的两个类:StringGenerator和ObjectIterator。字符串生成器StringGenerator工具类将对象转化为字符串,使对象可读性更好。可以用它来实现类的to
2、String方法或者把对象的字符串表达作为日志调试代码:123456789101112131415161718192021222324packagecom.stackhunter.util.tostring.example; importcom.stackhunter.example.employee.Department;importcom.stackhunter.example.employee.Employee;importcom.stackhunter.example.employee.Manager;importcom.stackhunter.example.p
3、eople.Person; importcom.stackhunter.util.tostring.StringGenerator; publicclassStringGeneratorExample{ publicstaticvoidmain(String[]args){ Departmentdepartment=newDepartment(5775,"Sales") .setEmployees( newEmployee(111,"Bill","Gates"), newEmp
4、loyee(222,"Howard","Schultz"), newManager(333,"Jeff","Bezos",75000)); System.out.println(StringGenerator.generate(department)); System.out.println(StringGenerator.generate(newint[]{111,222,333})); System.out.println(StringGenerator.generate(true));
5、} }StringGenerator.generate()将department,数组和boolean值进行格式化输出。12345678910111213141516171819202122com.stackhunter.example.employee.Department@129719f4 deptId=5775 employeeList=java.util.ArrayList@7037717a employeeList[0]=com.stackhunter.example.employee.Employee@17a323c0 firstName=
6、Bill id=111 lastName=Gates employeeList[1]=com.stackhunter.example.employee.Employee@57801e5f firstName=Howard id=222 lastName=Schultz employeeList[2]=com.stackhunter.example.employee.Manager@1c4a1bda budget=75000.0 firstName=Jeff id=333
7、lastName=Bezos name=Sales[I@39df3255 object[0]=111 object[1]=222 object[2]=333true对象迭代器ObjectIterator使用迭代器模式遍历对象的属性,以键值对形式保存。对象中的Javabean、集合、数组及map都要进行迭代。ObjectIterator也会考虑到对象之间循环引用的处理。123456789packagecom.stackhunter.util.tostring.example; importcom.stackhunter.
此文档下载收益归作者所有