ReflectiveVisitor

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:

  1. Visiting Collection elements
  2. Depth-first polymorphism

One thought on “ReflectiveVisitor

  1. 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.

     sub accept { my $visitor = shift; return ($fn = $visitor->can('visit_gouda')) ? $fn($self) : $self->SUPER::accept($visitor); } 

    Add in

    $visitor->can('visit_' . $self->name ) 

    if you want this to be dynamic and canonical.

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.