Inigo Surguy presents< an implementation of Visitor pattern based on reflection. I found useful a slight modification of it, that allows for visiting not only the narrowest type, but every type possible , based on the visitAll
flag: ReflectiveVisitor.java. This functionality comes in quite handy for tasks such as, for instance, validation. For example, if one has a complex class hierarchy (especially with multiple< inheritance) and different types have different requirements for it to be valid, and a concrete instance may implement a number of those, these validations can be well separated out.
See also:
Why is reflection so complicated in java? The following code in perl does the same thing — goes up the class heirarchy of the visited class, and finds a visitor method that works. As the untyped language junkie that I am, I wonder if it’s all the typing getting in the way? Or is it just silly to loop over class lists, maybe? In any case, thinking of function calls as messages, then the obvious query “does this class accept the message ‘visit_me’ ? ” makes this really easy.
Add in
if you want this to be dynamic and canonical.
LikeLike