Convert object to String using Iterator pattern
When manipulating JSOM, XML, Java beans and other objects, you may first think of the visitor pattern. But using the visitor pattern it is difficult to control callbacks from the calling code. For example, you cannot conditionally skip a branch from all callback sub-branches and leaf nodes. To solve this problem, you can use the Iterator pattern to traverse the entire object and generate a string that is easy for developers to read and debug. This iterator is quite versatile and I've used it in both tools for finding Java objects using XPath and logging exceptions in StackHunter.
API
This article mainly introduces two classes: StringGenerator and ObjectIterator.
String Generator
StringGenerator tool class converts objects into strings to make objects more readable. You can use it to implement the toString method of the class or use the string expression of the object as log debugging code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
StringGenerator.generate() formats department, array and boolean values to output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Object Iterator
ObjectIterator uses the iterator pattern to traverse the properties of the object and save them in the form of key-value pairs. Java beans, collections, arrays and maps in objects must be iterated. ObjectIterator also takes into account the handling of circular references between objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
Generates a collection of key-value pairs by traversing the entire object. Use the getValueAsString() method instead of toString() to format the output. Use the original toString() implementation for primitive types, wrapped types, strings, dates, and enumerations. For other types, the class name and hash value are output.
ObjectIterator.getDepth() will increase the indentation and make the output more readable. Use nextParent() before calling next() to shorten the current branch and jump to the next attribute.
1 2 3 4 5 6 |
|
Concrete implementation of Java object iterator
The first step to implement the iterator pattern is to create a general iterator interface: IObjectIterator. This interface can be used regardless of whether the traversed object is a Java bean, an array or a map.
1 2 3 4 5 |
|
Use this interface to obtain the name and value of the current attribute in a single order.
Classes that implement IObjectIterator are used to process objects of a certain type. Most classes call getName() to return the name prefix. ArrayIterator uses the index of the element: return name + "[" + nextIndex + "]";.
Property Iterator
PropertyIterator is probably the most important iteration class. It uses Java bean introspection to read object properties and convert them into a sequence of key-value pairs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
|
Array Iterator
ArrayIterator gets the length of the array through reflection, and then retrieves each data element. ArrayIterator does not care about the specific details of the value returned from the getValue() method. They are normally passed to PropertyIterator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
集合迭代器
CollectionIterator与ArrayIterator非常相似。使用java.lang.Iterable调用它的Iterable.iterator()方法初始化内部迭代器。
Map迭代器
MapIterator遍历java.util.Map的entry。它并不深入到每个entry的键值对,这个工作由MapEntryIterator类完成。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Map Entry迭代器
MapEntryIterator处理java.util.Map的单个entry。它只返回两个值:entry的键和值。与ArrayIterator及其他的类似,如果是复杂类型的话,它的结果可能最终传递给PropertyIterator,作为Java bean处理。
根迭代器
RootIterator返回单个元素——初始节点。可以把它想成XML文件的根节点。目的是发起整个遍历过程。
整合
ObjectIterator类作为门面角色(Facade),包装了所有的遍历逻辑。它根据最后一次getValue()的返回值类型决定哪个IObjectIterator的子类需要实例化。当子迭代器在内部创建时它在栈中保存当前迭代器的状态。它也暴露了getChild()和getDepth()方法为调用者展示当前进度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
字符串生成器的实现
已经看到如何遍历对象中的所有属性。最后的工作就是让输出更加美观,以及增加一些限制条件(比如不能创建一个GB级大小的字符串)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
代码第21行完成了格式化,增加了缩进和层次结构使显示更美观。
同时增加了一些限制条件:
第9行——限制字符串长度在16k内。
第13行——限制任何父节点下子节点数量小于64.
第21&25行——限制键和值长度在64个字符。
总结
本文介绍了如何使用迭代器模式遍历包含各种复杂属性的对象。关键是将每种类型的迭代委派给各自的类实现。可以在你自己的软件中使用这两个工具。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In Java programming, the Iterator and Iterable interfaces are important tools for processing elements in collections. The Iterator interface provides methods for iterative access to collection elements, while the Iterable interface defines the iterability of the collection so that the elements in the collection can be accessed through Iterator. The close cooperation between the two provides us with a general method for traversing collection elements. Iterator interface The Iterator interface defines the following methods: booleanhasNext(): Check whether there are still elements in the collection. Enext(): Returns the next element in the collection. voidremove(): Remove the current element. Iterable

Iterator interface The Iterator interface is an interface used to traverse collections. It provides several methods, including hasNext(), next() and remove(). The hasNext() method returns a Boolean value indicating whether there is a next element in the collection. The next() method returns the next element in the collection and removes it from the collection. The remove() method removes the current element from the collection. The following code example demonstrates how to use the Iterator interface to iterate over a collection: Listnames=Arrays.asList("John","Mary","Bob");Iterator

Conceptual differences: Iterator: Iterator is an interface that represents an iterator that obtains values from a collection. It provides methods such as MoveNext(), Current() and Reset(), allowing you to traverse the elements in the collection and operate on the current element. Iterable: Iterable is also an interface, representing an iterable object. It provides the Iterator() method, which returns an Iterator object to facilitate traversing the elements in the collection. Usage: Iterator: To use Iterator, you need to first obtain an Iterator object, and then call the MoveNext() method to move to the next

Introduction to IteratorIterator is an interface in Java for traversing collections. It provides a set of methods that allow you to access elements in a collection in a sequential manner. You can use Iterator to iterate over collection types such as List, Set, and Map. Demo code: Listlist=newArrayList();list.add("one");list.add("two");list.add("three");Iteratoriterator=list.iterator();while(iter

Iterator (Iterator) and Iterable object (Iterable) are two very important interfaces in the Java collection framework. They enable you to iterate over the elements in a collection without knowing the specific implementation of the collection. The Iterator interface defines methods for traversing collections, including hasNext() and next(). The hasNext() method checks if there are more elements in the collection, while the next() method returns the next element in the collection. The Iterable interface defines a method for creating an Iterator, the iterator() method. This method returns an Iterator object that can be used to iterate over the collection. The following is using Itera

Iterator interface The Iterator interface is a low-level interface in the Java collection framework for traversing collections. It defines two main methods: hasNext(): checks if there are more elements in the collection. next(): Returns the next element in the collection. The Iterator interface also defines some optional methods, such as the remove() method, which is used to remove the current element from the collection. Using the Iterator interface You can use the Iterator interface to traverse a collection using the following steps: Get the Iterator object of the collection. Use the hasNext() method to check if there are more elements in the collection. If there are more elements, use the next() method to get the next element

In Java, a collection is a collection of elements that provides a unified interface and methods to store, retrieve and operate these elements. Iterator and Iterable are two important Java interfaces that provide a common mechanism for traversing collection elements. The Iterator interface defines hasNext() and next() methods for traversing collections. The hasNext() method is used to check whether there are any untraversed elements in the collection, and the next() method is used to return the current element and move it to the next element. The Iterable interface defines the iterator() method, which returns an Iterator object for traversing the elements in the collection.

Interpretation of Java documentation: Detailed explanation of the usage of the iterator() method of the HashSet class. Specific code examples are required. In Java programming, HashSet is one of the commonly used collection classes. It implements the Set interface and inherits from the AbstractSet class. The iterator() method of the HashSet class is used to return an iterator object for traversing the elements in the HashSet. This article will explain in detail the usage of iterator() method of HashSet class, and
