2015-04-03 52 views
1

我正在使用java語法分析器,並且想要在某種方法(如main方法)中構建for語句。 我可以寫在屏幕上如何使用java解析器在AST中構建for語句?

(System.out.println("hello world") 

打印語句,但我不能建立一個for聲明。

+0

[可能回答你的問題(http://stackoverflow.com/questions/29111704/ eclipse-java-ast-parser-insert-statement-before-if-for-while) – issamux 2015-04-04 11:59:12

+0

你能告訴我你設法寫System.out.println嗎? – Chatz 2016-06-05 02:14:49

回答

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() { 
} 
} 

樣品項目github:issamux