使用Iterator模式将对象转成String.docx

  1. 1、本文档共13页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
操纵JSOM、XML、Java bean等对象时你可能最先想到访问者模式。但是使用访问者模式很难从调 用代码控制回调。比如,不能有条件的从所有回调的子分支和叶子节点跳过某个分支。解决这个问题 就可以使用Iterator模式遍历整个对象,生成易于开发者阅读和调试的字符串。该迭代器具备一定的 通用性,我在使用 XPath查找Java对象和在StackHunter中记录异常的工具中都用到了它 API 本文主要介绍的两个类:StringGenerator 和ObjectIterator 。 字符串生成器 StringGenerator 工具类将对象转化为字符串,使对象可读性更好。可以用它来实现类的toString 方法或者把对象的字符串表达作为日志调试代码: package com.stackhunter.util.tostring.example; 2 import com.stackhunter.example.employee.Department; import com.stackhunter.example.employee.Employee; import com.stackhunter.example.employee.Manager; import com.stackhunter.example.people.Person; 7 8 import com.stackhunter.util.tostring.StringGenerator; 9 10public class StringGeneratorExample { 11 public static void main(String[] args) { Department department = new Department(5775, "Sales") .setEmployees( new Employee(111, "Bill", "Gates"), newEmployee(222, "Howard", "Schultz"), new Manager(333, "Jeff", "Bezos", 1875000)); 19 System.out.println(StringGenerator.generate(departmen 21t)); 22 System.out.println(StringGenerator.generate(new int[] 23{ 111,222, 333 })); 24 System.out.println(StringGenerator.generate(true)); StringGenerator.generate()将department,数组和boolean值进行格式化输出。 StringGenerator.generate() 12 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 employeeList = java.util.ArrayList@7037717a employeeList[0]= com.stackhunter.example.employee.Employee@17a323c0 firstName = 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 lastName = Bezos name = Sales [I@39df3255 object[0] = 111 object[1] = 222 object[2] = 333 true 对象迭代器 ObjectIterator 使用迭代器模式遍历对象的属性, 以键值对形式保存。对象中的Java bean、集合、 数组及map都要进行迭代。ObjectIterator 也会考虑到对象之间循环引用的处理。 1 package com.stackhunter.util.tostring.example; 2 import com.stackhunter.example.employee.Department; import com.stackhunter.example.employee.Employee; import co

文档评论(0)

yj1028 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档