我使用独立ASTParser读取变量名,但它只显示了第一个声明的变量。这可能是因为添加了bw.close(),但我无法将它放在其他地方。此外,当只调用一次构造函数时,我无法理解CompilationUnit的方法如何能够打印所有声明的变量。
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
cu.accept(new ASTVisitor() {
Set names = new HashSet();
BufferedWriter bw = new BufferedWriter(fw);
public boolean visit(VariableDeclarationFragment node) {
SimpleName name = node.getName();
this.names.add(name.getIdentifier());
try {
bw.write("writin");
bw.write("Declaration of '"+name+"' at line"+cu.getLineNumber(name.getStartPosition()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false; // do not continue to avoid usage info
}
});发布于 2014-03-31 11:33:08
没有看到你的全部代码,我只能猜测.
从您说的,我相信,您是在调用bw.close()在您的visit方法?您应该对此进行更改,因此在访问完成后,BufferedWriter只会关闭(并被刷新)。为此,在访问者作用域之外声明一个final BufferedWriter bw变量,然后在一个close()块中进行close()。
下面是一个完整的例子:
public static void parse(String fileContent) {
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(fileContent.toCharArray());
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
final StringWriter writer = new StringWriter();
final BufferedWriter bw = new BufferedWriter(writer);
try{
cu.accept(new ASTVisitor() {
public boolean visit(VariableDeclarationFragment node) {
SimpleName name = node.getName();
try {
bw.write("writing ");
bw.write("Declaration of '"+name+"' at line "+cu.getLineNumber(name.getStartPosition()));
bw.write("\n");
} catch (IOException e) {
e.printStackTrace();
}
return false; // do not continue to avoid usage info
}
});
} finally{
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(writer.getBuffer());
}如果将以下类用作(文本)输入,
class TestClass{
private Object field1;
private Object field2;
}您应该看到与此类似的输出:
writing Declaration of 'field1' at line 4
writing Declaration of 'field2' at line 5https://stackoverflow.com/questions/22759432
复制相似问题