KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > spoon > examples > visitor > processing > AbstractVisitorProcessor


1 package spoon.examples.visitor.processing;
2
3 import spoon.examples.visitor.template.VisitorTemplate;
4 import spoon.processing.AbstractProcessor;
5 import spoon.reflect.declaration.CtClass;
6 import spoon.reflect.declaration.CtType;
7 import spoon.reflect.declaration.ModifierKind;
8 import spoon.reflect.reference.CtTypeReference;
9 import spoon.template.Substitution;
10 import spoon.template.Template;
11
12 /**
13  * The abstract processor {@link AbstractVisitorProcessor} introduces an
14  * {@link spoon.examples.visitor.template.VisitorTemplate#accept(_Visitor_)}
15  * template method in all the classes that are a sub-type of a root type (the
16  * root node of the visited hierarchy, given by {@link #getVisitedRootType()}).
17  *
18  * <p>
19  * By automatically generating the <code>accept</code> method, this processor
20  * makes the visitor pattern more generic an easier to use. In particular, any
21  * change in the visited hierarchy will be automatically detected when spooning
22  * the program with this processor.
23  *
24  * <p>
25  * Note that this abstract class must be subclassed to tune it to a particular
26  * visitor pattern (see {@link #getVisitedInterface()},
27  * {@link #getVisitedRootType()}, {@link #getVisitorType()}, and an example
28  * implementation
29  * {@link spoon.examples.visitor.processing.PrintExpressionVisitorProcessor}).
30  *
31  * @see spoon.examples.visitor.template.VisitorTemplate
32  */

33 public abstract class AbstractVisitorProcessor extends
34         AbstractProcessor<CtType<?>> {
35
36     /**
37      * Defines the root node of the visited type hierarchy.
38      */

39     public abstract CtTypeReference<?> getVisitedRootType();
40
41     /**
42      * Defines the actual visitor type (typically a root interface for all the
43      * visitor).
44      */

45     public abstract CtTypeReference<?> getVisitorType();
46
47     /**
48      * Defines the actual visited type.
49      */

50     public abstract CtTypeReference<?> getVisitedInterface();
51
52     public boolean isToBeProcessed(CtType<?> candidate) {
53         return getVisitedRootType().isAssignableFrom(
54                 getFactory().Type().createReference(candidate));
55     }
56
57     public void process(CtType<?> target) {
58         // insert visited interface
59
if (target == getVisitedRootType().getDeclaration()) {
60             target.getSuperInterfaces().add(getVisitedInterface());
61         }
62         // insert the accept method
63
if (target instanceof CtClass
64                 && !target.hasModifier(ModifierKind.ABSTRACT)) {
65             Template t = new VisitorTemplate(target.getSimpleName(),
66                     getVisitorType().getActualClass());
67             Substitution.insertAll(target, t);
68         }
69     }
70
71 }
72
Popular Tags