KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > picocontainer > defaults > AbstractPicoVisitor


1 /*****************************************************************************
2  * Copyright (C) PicoContainer Organization. All rights reserved. *
3  * ------------------------------------------------------------------------- *
4  * The software in this package is published under the terms of the BSD *
5  * style license a copy of which has been included with this distribution in *
6  * the LICENSE.txt file. *
7  *****************************************************************************/

8 package org.picocontainer.defaults;
9
10 import org.picocontainer.PicoVisitor;
11
12 import java.lang.reflect.InvocationTargetException JavaDoc;
13 import java.lang.reflect.Method JavaDoc;
14
15 /**
16  * Abstract PicoVisitor implementation. A generic traverse method is implemented, that
17  * accepts any object with a method named "accept", that takes a
18  * {@link PicoVisitor} as argument and and invokes it. Additionally it provides the
19  * {@link #checkTraversal()} method, that throws a {@link PicoVisitorTraversalException},
20  * if currently no traversal is running.
21  *
22  * @author Jörg Schaible
23  * @since 1.1
24  */

25 public abstract class AbstractPicoVisitor implements PicoVisitor {
26     private boolean traversal;
27     
28     public Object JavaDoc traverse(Object JavaDoc node) {
29         traversal = true;
30         try {
31             final Method JavaDoc accept = node.getClass().getMethod("accept", new Class JavaDoc[]{PicoVisitor.class});
32             accept.invoke(node, new Object JavaDoc[]{this});
33             return Void.TYPE;
34         } catch (NoSuchMethodException JavaDoc e) {
35         } catch (IllegalAccessException JavaDoc e) {
36         } catch (InvocationTargetException JavaDoc e) {
37             Throwable JavaDoc cause = e.getTargetException();
38             if (cause instanceof RuntimeException JavaDoc) {
39                 throw (RuntimeException JavaDoc)cause;
40             } else if (cause instanceof Error JavaDoc) {
41                 throw (Error JavaDoc)cause;
42             }
43         } finally {
44             traversal = false;
45         }
46         throw new IllegalArgumentException JavaDoc(node.getClass().getName() + " is not a valid type for traversal");
47     }
48
49     /**
50      * Checks the traversal flag, indicating a currently running traversal of the visitor.
51      * @throws PicoVisitorTraversalException if no traversal is active.
52      */

53     protected void checkTraversal() {
54         if (!traversal) {
55             throw new PicoVisitorTraversalException(this);
56         }
57     }
58 }
59
Popular Tags