JavaJDT解析器。获取VariableDeclarationFragment的变量类型
我已经用JDT实现了一个Java解析器,但我不知道当变量的节点类型是VariableDeclarationFragment时如何获取变量类型 我发现只有在涉及VariableDeclaration时才能获得变量类型 我的代码如下JavaJDT解析器。获取VariableDeclarationFragment的变量类型,java,eclipse-jdt,Java,Eclipse Jdt,我已经用JDT实现了一个Java解析器,但我不知道当变量的节点类型是VariableDeclarationFragment时如何获取变量类型 我发现只有在涉及VariableDeclaration时才能获得变量类型 我的代码如下 public boolean visit(VariableDeclarationFragment node) { SimpleName name = node.getName(); System.out.println("Declaration of
public boolean visit(VariableDeclarationFragment node) {
SimpleName name = node.getName();
System.out.println("Declaration of '" + name + "' of type '??');
return false; // do not continue
}
有人能帮我吗?根据,
VariableDeclarationFragment
扩展了VariableDeclarationFragment
,因此您可以使用相同的方法来获取其中任何一个的类型。我刚刚知道如何从VariableDeclarationFragment获取类型。我只需要得到它的父级,即FieldDeclaration,然后我就可以访问它的变量类型。这可能不是最好的类型安全解决方案,但它对我的情况有效。我只是通过调用toString()方法来提取节点中正在处理的类型 通过检查节点的类型,以及前面声明的EXIT_节点类列表的简单名称,我对自己的位置非常有信心
有一点。实际上,当涉及到VariableDeclaration时,我使用getStructuralProperty(SingleVariableDeclaration.type_属性)获取变量类型。但是,我已经尝试在VariableDeclarationFragment中调用了相同的方法,然后它抛出了一个异常,表示该节点没有这个异常property@MarceloNoguti我的猜测是,
variabledclarationfragment
不一定包含类型信息。这毕竟是一个片段,我对此做了很多研究。恐怕你是对的,真遗憾。我想我必须解决这个问题。实际上,它也可以是VariableDeclarationStatement或VariableDeclarationExpression。
public boolean visit(VariableDeclarationFragment node) {
SimpleName name = node.getName();
String typeSimpleName = null;
if(node.getParent() instanceof FieldDeclaration){
FieldDeclaration declaration = ((FieldDeclaration) node.getParent());
if(declaration.getType().isSimpleType()){
typeSimpleName = declaration.getType().toString();
}
}
if(EXIT_NODES.contains(typeSimpleName)){
System.out.println("Found expected type declaration under name "+ name);
}
return false;
}