我使用Standalone ASTParser来读取变量名,但它只显示了第一个声明的变量。这可能是因为增加了 bw.close(),但我无法得到它的其他地方。此外,我无法理解当只调用一次ASTParser构造函数时,CompilationUnit的 accept 方法如何打印所有声明的变量。
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
}
});
答案 0 :(得分:1)
没有看到你的整个代码,我只能猜测......
根据您的说法,我相信您在bw.close()
方法期间在某个地方致电visit
?您应该更改它,因此BufferedWriter
仅在访问完成后关闭(并刷新)。为此,请在访问者范围之外声明final BufferedWriter bw
变量,然后在finally块中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 5