我正在使用java解析器,我想在某个方法(如main方法)中构建for
语句。
我可以写一个在屏幕上打印的声明
(System.out.println("hello world")
但是我无法构建for
语句。
答案 0 :(得分:2)
我正在使用项目com.github.javaparser:
public static void main(String[] args) {
// creates an input stream for the file to be parsed
FileInputStream in;
try {
in = new FileInputStream("test.java");
try {
// parse the file
CompilationUnit cu = JavaParser.parse(in);
new MyMethodVisitor().visit(cu, null);
} catch (ParseException e) {
e.printStackTrace();
} finally {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//方法访客
private static class MyMethodVisitor extends VoidVisitorAdapter {
@Override
public void visit(MethodDeclaration method, Object arg) {
//
System.out.println("method body : " + method.toString());
System.out.println("*******************************");
//
addForStmt(method.getBody());
//
System.out.println("method body : " + method.toString());
//
}
private void addForStmt(BlockStmt body) {
int beginLine = body.getBeginLine();
int beginColumn = body.getBeginColumn();
int endLine = body.getEndLine();
int endColumn = body.getEndColumn();
//
List<Expression> init = new ArrayList<Expression>();
Expression compare = null;
List<Expression> update = null;
BlockStmt methodBody = new BlockStmt();
ForStmt forStmt = new ForStmt(beginLine, beginColumn, endLine, endColumn, init, compare, update, methodBody);
//
ASTHelper.addStmt(body, forStmt);
}
}
<强>输出:强>
[前]
method body : public void forStatementMethod() {}
[后]
method body : public void forStatementMethod() {
for (; ; ) {
}
}
// test.java
public class test<E> {
public void forStatementMethod() {
}
}
中的示例项目