本文主要是介绍【代码重构 JDT】遍历AST,获取每个节点的所有直接子节点,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class DataNode {public ASTNode node; //所代表的的AST节点public int label; //编号public List<Integer> childrenLables = new ArrayList<>(); //直接的子节点的编号public List<ASTNode> childrenNodes = new ArrayList<>(); //直接的子节点public boolean isLeaf = false; //是否是叶子节点public String nodeType = "unknown";
}public static int ID = 0; //用来编号// 输入的是CompilationUnit根节点, label为0
public static void getDirectChildren(ASTNode node, int label, Map<Integer, DataNode> Nodes){//先创建一个节点数据结构DataNode myNode = new DataNode();Nodes.put(label, myNode);myNode.label = label;myNode.node = node;myNode.nodeType = node.getClass().toString();List listProperty = node.structuralPropertiesForType();boolean hasChildren = false;for(int i = 0; i < listProperty.size(); i++){StructuralPropertyDescriptor propertyDescriptor = (StructuralPropertyDescriptor) listProperty.get(i);if(propertyDescriptor instanceof ChildListPropertyDescriptor){//ASTNode列表ChildListPropertyDescriptor childListPropertyDescriptor = (ChildListPropertyDescriptor)propertyDescriptor;Object children = node.getStructuralProperty(childListPropertyDescriptor);List<ASTNode> childrenNodes = (List<ASTNode>)children;for(ASTNode childNode: childrenNodes){//获取所有节点if(childNode == null)continue;hasChildren = true;myNode.childrenNodes.add(childNode);myNode.childrenLables.add((++ID));getDirectChildren(childNode, ID, Nodes);//继续递归//System.out.println("childrenList: "+childNode+" "+childNode.getClass());}}else if(propertyDescriptor instanceof ChildPropertyDescriptor){//一个ASTNodeChildPropertyDescriptor childPropertyDescriptor = (ChildPropertyDescriptor)propertyDescriptor;Object child = node.getStructuralProperty(childPropertyDescriptor);ASTNode childNode = (ASTNode)child;if(childNode == null)continue;hasChildren = true;//获取了这个节点myNode.childrenNodes.add(childNode);myNode.childrenLables.add((++ID));getDirectChildren(childNode, ID, Nodes);//继续递归//System.out.println("child: "+childNode +" "+childNode.getClass());}}if(hasChildren){//进行递归子节点myNode.isLeaf = false;}else{//结束,是叶子结点myNode.isLeaf = true;}
}
这篇关于【代码重构 JDT】遍历AST,获取每个节点的所有直接子节点的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!