Home | History | Annotate | Download | only in javaparser
      1 /*
      2  * Copyright (C) 2007-2010 Jlio Vilmar Gesser.
      3  * Copyright (C) 2011, 2013-2016 The JavaParser Team.
      4  *
      5  * This file is part of JavaParser.
      6  *
      7  * JavaParser can be used either under the terms of
      8  * a) the GNU Lesser General Public License as published by
      9  *     the Free Software Foundation, either version 3 of the License, or
     10  *     (at your option) any later version.
     11  * b) the terms of the Apache License
     12  *
     13  * You should have received a copy of both licenses in LICENCE.LGPL and
     14  * LICENCE.APACHE. Please refer to those files for details.
     15  *
     16  * JavaParser is distributed in the hope that it will be useful,
     17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     19  * GNU Lesser General Public License for more details.
     20  */
     21 
     22 package com.github.javaparser;
     23 
     24 import com.github.javaparser.ast.Node;
     25 import com.github.javaparser.ast.observer.Observable;
     26 
     27 import java.util.Optional;
     28 
     29 /**
     30  * An object that has a parent node.
     31  */
     32 public interface HasParentNode<T> extends Observable {
     33 
     34     /**
     35      * Return the parent node or null, if no parent is set.
     36      */
     37     Optional<Node> getParentNode();
     38 
     39     /**
     40      * Set the parent node.
     41      *
     42      * @param parentNode the parent node or null, to set no parent
     43      * @return return <i>this</i>
     44      */
     45     T setParentNode(Node parentNode);
     46 
     47     /**
     48      * <i>this</i> for everything except NodeLists. NodeLists use their parent as their children parent.
     49      */
     50     Node getParentNodeForChildren();
     51 
     52     /**
     53      * Get the ancestor of the node having the given type, or null if no ancestor of the given type is found.
     54      */
     55     default <N> Optional<N> getAncestorOfType(Class<N> classType) {
     56         Node parent = getParentNode().orElse(null);
     57         while (parent != null) {
     58             if (classType.isAssignableFrom(parent.getClass())) {
     59                 return Optional.of(classType.cast(parent));
     60             }
     61             parent = parent.getParentNode().orElse(null);
     62         }
     63         return Optional.empty();
     64     }
     65 }
     66