Java Tip: Use Reflection to implement the Visitor Mode
Overview
The Visitor mode is commonly used to separate the structure of an object set from the operations executed on the set. For example, it can separate the analysis logic in a compiler from the code generation logic. With such separation, it is easy to use different code generators. The greater benefit is that some other utilities, such as lint, can use the analysis logic while avoiding the fatigue of the code generation logic. Unfortunately, adding new objects to a set often requires modifying the already written Visitor class. This article proposes a more flexible way to implement the Visitor mode in Java: Using Reflection (Reflection ).
-------------------------------------------------------------
Collections are widely used in object-oriented programming, but they often lead to code-related questions. For example, "If a set has different objects, how can I perform operations on it? "
One way is to iterate each element in the set, and then perform corresponding operations on each element based on the class. This is difficult, especially if you do not know what types of objects are in the collection. For example, if you want to print the elements in the set, you can write the following method ):
Public void messyPrintCollection (Collection collection ){
Iterator iterator = collection. iterator ()
While (iterator. hasNext ())
System. out. println (iterator. next (). toString ())
}
This seems simple enough. It only calls the Object. toString () method and prints the Object, right? But what if there is a group of hash tables? It will become complicated. You must check the type of the objects returned from the collection:
Public void messyPrintCollection (Collection collection ){
Iterator iterator = collection. iterator ()
While (iterator. hasNext ()){
Object o = iterator. next ();
If (o instanceof Collection)
MessyPrintCollection (Collection) o );
Else
System. out. println (o. toString ());
}
}
Yes. Now we have solved the nested set problem, but it requires the object to return a String. What if there are other objects that do not return a String? What if I want to add quotation marks before and after the String object and add f after the Float object? The code is getting more and more complex: