我正在尝试获取变量的类型信息。这是我正在使用的代码:
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
public class ASTTester {
public static void main(String[] args) {
String str = "package test; import java.util.ArrayList; public class Apple { public static void main(String[] args) { ArrayList<String> al = null; int j =0; }}";
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setSource(str.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setResolveBindings(true);
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
TypeFinderVisitor v = new TypeFinderVisitor();
cu.accept(v);
}
}
class TypeFinderVisitor extends ASTVisitor{
public boolean visit(VariableDeclarationStatement node){
System.out.println(node.getType());
for (Iterator iter = node.fragments().iterator(); iter.hasNext();) {
VariableDeclarationFragment fragment = (VariableDeclarationFragment) iter.next();
System.out.println(fragment.getName());
IVariableBinding binding = fragment.resolveBinding();
System.out.println("binding: " +binding);
}
return true;
}
}
输出结果为:
ArrayList<String>
al
binding: null
int
j
binding: null
我不明白为什么绑定为null,因为我明确地将绑定设置为true。