org.eclipse.jdt.core.dom.ASTNode的子节点
使用Eclise JDT,我需要检索任何ASTNode的子节点。 我可以使用某个实用方法吗?
我现在能想到的唯一方法是inheritanceASTVisitor并手动处理每种节点以找到它的子节点。 但研究每种节点类型需要做很多工作。
我将从查看ASTView插件的来源开始,因为它也做同样的事情。
基于代码
- org.eclipse.jdt.astview.views.ASTViewContentProvider.getNodeChildren(ASTNode)
- org.eclipse.jdt.astview.views.NodeProperty.getChildren()
所需的代码看起来应该是这样的
public Object[] getChildren(ASTNode node) { List list= node.structuralPropertiesForType(); for (int i= 0; i < list.size(); i++) { StructuralPropertyDescriptor curr= (StructuralPropertyDescriptor) list.get(i); Object child= node.getStructuralProperty(curr); if (child instanceof List) { return ((List) child).toArray(); } else if (child instanceof ASTNode) { return new Object[] { child }; } return new Object[0]; } }
我们可以使用以下API将子元素检索为ASTNode列表:
ASTNode.getStructureProperty(StructuralPropertyDescriptor property)
它返回此节点的给定结构属性的值。 返回的值取决于属性的类型:
SimplePropertyDescriptor - the value of the given simple property, or null if none; primitive values are "boxed" ChildPropertyDescriptor - the child node (type ASTNode), or null if none ChildListPropertyDescriptor - the list (element type: ASTNode)
但是, ChildListPropertyDescripor
不打算由客户端实例化。 您可以参考我的代码来获取子项列表:
public static List getChildren(ASTNode node) { List children = new ArrayList (); List list = node.structuralPropertiesForType(); for (int i = 0; i < list.size(); i++) { Object child = node.getStructuralProperty((StructuralPropertyDescriptor)list.get(i)); if (child instanceof ASTNode) { children.add((ASTNode) child); } } return children; }