media media - 1 year ago 89
Java Question

How to create a new object as an AST node using JavaParser?

I would like to add the following statement to my AST using JavaParser. I already read the manual and I know how to do simple examples. However, I could not find anything related to creating new objects. I am wondering if anyone could help me with that.

PrintWriter out = new PrintWriter(new FileWriter("path", true));

Answer Source

My advice when trying to do something like this is simple: put this code in a String, parse it with JavaParser and you get the piece of AST you want.

In the past you add to put this code inside a class and parse the whole file while today you can just use:

Statement pieceOfAST = JavaParser.parseStatement("<the code of my statement>");

Now, if you want you could check the structure of this code and recreate programmatically or you just take the piece of AST you got from parsing and you add it where you need. You can also use the clone to get more copies of it and use it more than once.

Disclaimer: I am a JavaParser contributor

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download