![](/img/trans.png)
[英]Eclipse JDT AST: check if SimpleName is a variable identifier
[英]Extracting all variable names from Variable declarations using Eclipse JDT
我一直在使用Eclipse JDT分析源代码。 目前,我有一个程序能够获取一些代码,将其转换为AST然后进行一些注释。
现在,我想要做的是,对于每个变量声明,获取所涉及的所有变量。 例如:
int a = 10;
它很容易,只是变量a
但是在以下情况下:
int a = b +c ;
我需要分析正确的部分并提取每个变量。 我到现在所拥有的是:
对于每个变量声明:
//get the fragment
List<VariableDeclarationFragment> ff = vds_p.fragments();
//foreach fragment, get the name of the variable and the value associated
for(VariableDeclarationFragment f_p : ff){
SimpleName name = f_p.getName();
Expression exp = f_p.getInitializer();
ChildPropertyDescriptor exp_prop = f_p.getInitializerProperty();
System.out.println("name: "+name);
System.out.println("expression: "+exp);
}
因此,我能够获取变量的名称和分配给它的表达式。 现在,这是我的问题:
如何使用JDT分析分配给变量的表达式,例如
int a = b + c ;
我想得到b
和c
。 我知道我可以获取“ b + c”字符串并根据运算符应用手动解析,但是我想知道是否有使用JDT的自动化方式
谢谢!
基本上,您正在寻找具有'org.eclipse.jdt.core.dom.IVariableBinding'的'org.eclipse.jdt.core.dom.SimpleName'节点。 您应该创建一个'org.eclipse.jdt.core.dom.ASTVisitor'并覆盖'org.eclipse.jdt.core.dom.ASTVisitor.visit(SimpleName)'。 然后使用ASTVisitor分析变量声明的右侧表达式。
您可能会发现的“如何找到一个AST节点”部分这篇文章有用。 您可能还会发现AST View插件很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.