/** * Clone the given {@link Node} and its sub nodes recursively. This method * handles shared nodes correctly. * * @param <T> The type of the node. * @param node the root of the graph to clone. * @return a clone of the given graph of node. */ public static <T extends Node> T cloneGraph(final T node) { return cloneGraph(node, new IdentityHashMap<Node, Node>()); }
@SuppressWarnings("unchecked") private static <T extends Node> T cloneGraph(final T node, final Map<Node, Node> clonedNodes) { T clone = (T) clonedNodes.get(node); if (clone == null) { clone = cloneNodeState(node); // add sub nodes for (final String subNodeType : node.astGetNodeTypes()) { for (final Node subNode : node.astGetNodes(subNodeType)) { if (subNode != null) clone.astAddNode(cloneGraph(subNode, clonedNodes)); } } clonedNodes.put(node, clone); } return clone; }