Children of org.eclipse.jdt.core.dom.ASTNode

老子叫甜甜 提交于 2019-11-29 21:14:51

问题


Using Eclise JDT, I need to retrieve the children of any ASTNode. Is there a utility method somewhere that I could use ?

The only way I can think of right now is to subclass ASTVisitor and treat each kind of node manually to find its children. But it's a lot of work to study every node type.


回答1:


I would start by looking at source of ASTView Plugin, since that also does the same thing.

Based on the code in

  • org.eclipse.jdt.astview.views.ASTViewContentProvider.getNodeChildren(ASTNode)
  • org.eclipse.jdt.astview.views.NodeProperty.getChildren()

the required code should look something like this

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];
    }
}



回答2:


We can retrieve the children as an ASTNode List using the API of :

ASTNode.getStructureProperty(StructuralPropertyDescriptor property)

It returns the value of the given structural property for this node. The value returned depends on the kind of 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)

However, the ChildListPropertyDescripor is not intended to be instantiated by clients. You can refer to my code to get the list of children:

public static List<ASTNode> getChildren(ASTNode node) {
    List<ASTNode> children = new ArrayList<ASTNode>();
    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;
}


来源:https://stackoverflow.com/questions/11841789/children-of-org-eclipse-jdt-core-dom-astnode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!