Class Node

  • All Implemented Interfaces:
    NodeWithRange<Node>, NodeWithTokenRange<Node>, Observable, Visitable, HasParentNode<Node>, Cloneable
    Direct Known Subclasses:
    ArrayCreationLevel, BodyDeclaration, CatchClause, Comment, CompilationUnit, Expression, ImportDeclaration, MemberValuePair, ModuleDeclaration, ModuleStmt, Name, PackageDeclaration, Parameter, SimpleName, Statement, Type, VariableDeclarator

    public abstract class Node
    extends Object
    implements Cloneable, HasParentNode<Node>, Visitable, NodeWithRange<Node>, NodeWithTokenRange<Node>
    Base class for all nodes of the abstract syntax tree.

    Construction

    The tree is built by instantiating the required nodes, then adding them to other nodes. If it is the parser who is building the tree, it will use the largest constructor, the one with "range" as the first parameter. If you want to manually instantiate nodes, we suggest to...

    • use a convenience method, like "addStatement(...)", or if none are available...
    • use a convenient constructor, like ClassOrInterfaceType(String name), or if none are available...
    • use the default constructor.
    • Alternatively, use one of the JavaParser.parse(snippet) methods.
    ... and use the various methods on the node to initialize it further, if needed.

    Parent/child

    The parent node field is managed automatically and can be seen as read only. Note that there is only one parent, and trying to use the same node in two places will lead to unexpected behaviour. It is advised to clone() a node before moving it around.

    Comments

    Each Node can have one associated comment which describes it and a number of "orphan comments" which it contains but are not specifically associated to any child.

    Positions

    When the parser creates nodes, it sets their source code position in the "range" field. When you manually instantiate nodes, their range is not set. The top left character is position 1, 1. Note that since this is an abstract syntax tree, it leaves out a lot of text from the original source file, like where braces or comma's are exactly. Therefore there is no position information on everything in the original source file.

    Observers

    It is possible to add observers to the the tree. Any change in the tree is sent as an event to any observers watching.

    Visitors

    The most comfortable way of working with an abstract syntax tree is using visitors. You can use one of the visitors in the visitor package, or extend one of them. A visitor can be "run" by calling accept on a node:

    node.accept(visitor, argument);
    where argument is an object of your choice (often simply null.)
    Author:
    Julio Vilmar Gesser
    • Constructor Detail

    • Method Detail

      • customInitialization

        protected void customInitialization()
        Called in every constructor for node specific code. It can't be written in the constructor itself because it will be overwritten during code generation.
      • getComment

        @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
        public Optional<Comment> getComment()
        This is a comment associated with this node.
        Returns:
        comment property
      • setRange

        public Node setRange​(Range range)
        Specified by:
        setRange in interface NodeWithRange<Node>
        Parameters:
        range - the range of characters in the source code that this node covers. null can be used to indicate that no range information is known, or that it is not of interest.
      • setComment

        public final Node setComment​(Comment comment)
        Use this to store additional information to this node.
        Parameters:
        comment - to be set
      • setLineComment

        public final Node setLineComment​(String comment)
        Use this to store additional information to this node.
        Parameters:
        comment - to be set
      • setBlockComment

        public final Node setBlockComment​(String comment)
        Use this to store additional information to this node.
        Parameters:
        comment - to be set
      • toString

        public final String toString()
        Return the String representation of this node.
        Overrides:
        toString in class Object
        Returns:
        the String representation of this node
      • hashCode

        public final int hashCode()
        Overrides:
        hashCode in class Object
      • getChildNodes

        public List<Node> getChildNodes()
        Contains all nodes that have this node set as their parent. You can add nodes to it by setting a node's parent to this node. You can remove nodes from it by setting a child node's parent to something other than this node.
        Returns:
        all nodes that have this node as their parent.
      • addOrphanComment

        public void addOrphanComment​(Comment comment)
      • removeOrphanComment

        public boolean removeOrphanComment​(Comment comment)
      • getOrphanComments

        public List<Comment> getOrphanComments()
        This is a list of Comment which are inside the node and are not associated with any meaningful AST Node.

        For example, comments at the end of methods (immediately before the parenthesis) or at the end of CompilationUnit are orphan comments.

        When more than one comment preceeds a statement, the one immediately preceding it it is associated with the statements, while the others are orphans.

        Changes to this list are not persisted.

        Returns:
        all comments that cannot be attributed to a concept
      • getAllContainedComments

        public List<Comment> getAllContainedComments()
        This is the list of Comment which are contained in the Node either because they are properly associated to one of its children or because they are floating around inside the Node
        Returns:
        all Comments within the node as a list
      • setParentNode

        public Node setParentNode​(Node newParentNode)
        Assign a new parent to this node, removing it from the list of children of the previous parent, if any.
        Specified by:
        setParentNode in interface HasParentNode<Node>
        Parameters:
        newParentNode - node to be set as parent
        Returns:
        return this
      • setAsParentNodeOf

        protected void setAsParentNodeOf​(Node childNode)
      • hasComment

        @Deprecated
        public boolean hasComment()
        Deprecated.
        use getComment().isPresent()
      • tryAddImportToParentCompilationUnit

        public void tryAddImportToParentCompilationUnit​(Class<?> clazz)
      • getChildNodesByType

        public <N extends NodeList<N> getChildNodesByType​(Class<N> clazz)
        Recursively finds all nodes of a certain type.
        Parameters:
        clazz - the type of node to find.
      • getNodesByType

        @Deprecated
        public <N extends NodeList<N> getNodesByType​(Class<N> clazz)
        Deprecated.
        use getChildNodesByType
      • getData

        public <M> M getData​(DataKey<M> key)
        Gets data for this component using the given key.
        Type Parameters:
        M - The type of the data.
        Parameters:
        key - The key for the data
        Returns:
        The data or null of no data was found for the given key
        See Also:
        DataKey
      • setData

        public <M> void setData​(DataKey<M> key,
                                M object)
        Sets data for this component using the given key. For information on creating DataKey, see DataKey.
        Type Parameters:
        M - The type of data
        Parameters:
        key - The singleton key for the data
        object - The data object
        See Also:
        DataKey
      • remove

        public boolean remove()
        Try to remove this node from the parent
        Returns:
        true if removed, false if it is a required property of the parent, or if the parent isn't set.
        Throws:
        RuntimeException - if it fails in an unexpected way
      • replace

        public boolean replace​(Node node)
        Try to replace this node in the parent with the supplied node.
        Returns:
        true if removed, or if the parent isn't set.
        Throws:
        RuntimeException - if it fails in an unexpected way
      • removeForced

        public void removeForced()
        Forcibly removes this node from the AST. If it cannot be removed from the parent with remove(), it will try to remove its parent instead, until it finds a node that can be removed, or no parent can be found.

        Since everything at CompilationUnit level is removable, this method will only (silently) fail when the node is in a detached AST fragment.

      • setAsParentNodeOf

        protected void setAsParentNodeOf​(NodeList<? extends Node> list)
      • notifyPropertyChange

        public <P> void notifyPropertyChange​(ObservableProperty property,
                                             P oldValue,
                                             P newValue)
      • unregister

        public void unregister​(AstObserver observer)
        Description copied from interface: Observable
        Unregister an observer. If the given observer was not registered there are no effects.
        Specified by:
        unregister in interface Observable
      • register

        public void register​(AstObserver observer,
                             Node.ObserverRegistrationMode mode)
        Register a new observer for the given node. Depending on the mode specified also descendants, existing and new, could be observed. For more details see ObserverRegistrationMode.
      • registerForSubtree

        public void registerForSubtree​(AstObserver observer)
        Register the observer for the current node and all the contained node and nodelists, recursively.
      • isRegistered

        public boolean isRegistered​(AstObserver observer)
        Description copied from interface: Observable
        Was this observer registered? Note that equals is used to determine if the given observer was registered.
        Specified by:
        isRegistered in interface Observable
      • getNodeLists

        public List<NodeList<?>> getNodeLists()
        The list of NodeLists owned by this node.
      • remove

        @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
        public boolean remove​(Node node)
      • removeComment

        @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
        public Node removeComment()
      • clone

        @Generated("com.github.javaparser.generator.core.node.CloneGenerator")
        public Node clone()
        Overrides:
        clone in class Object
      • getMetaModel

        @Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
        public NodeMetaModel getMetaModel()
        Returns:
        get JavaParser specific node introspection information.
      • getParsed

        public Node.Parsedness getParsed()
        Returns:
        whether this node was successfully parsed or not. If it was not, only the range and tokenRange fields will be valid.
      • setParsed

        public Node setParsed​(Node.Parsedness parsed)
        Used by the parser to flag unparsable nodes.
      • replace

        @Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
        public boolean replace​(Node node,
                               Node replacementNode)