Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
Lucas Gontijo
I would like to translate the book "JavaParser: Visited" into Brazilian Portuguese, has anyone translated this book? do you know if it is allowed? who would i have to talk to? thank you.
Danny van Bruggen
@SmiddyPence is/was the book guy.
Luca Molteni
Hi guys, I haven't been checking this channel for a while
so @matozoid aren't you on the project anymore? woah that's big news
I hope there's still someone then :D
Little trivia: what is the difference between the twos? (without looking at the source code
     StringLiteralExpr a = new StringLiteralExpr("String with \"");
     StringLiteralExpr b = new StringLiteralExpr().setString("String with \"");
Cameron Braid
I have a method call chain like the following, a.b().c() and I want to insert an extra method call in the chain to make it like a.b().d().c(). How do I do that ? I tried using new MethodCallExpr making d's scope be b and c's scope be d but when printing I get
Exception in thread "main" java.util.NoSuchElementException: No value present
        at java.base/java.util.Optional.get(Optional.java:148)
        at com.github.javaparser.printer.lexicalpreservation.PhantomNodeLogic.isPhantomNode(PhantomNodeLogic.java:58)
        at com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter.findNodeForToken(LexicalPreservingPrinter.java:364)
        at com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter.findNodeForToken(LexicalPreservingPrinter.java:375)
        at com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter.findNodeForToken(LexicalPreservingPrinter.java:375)
My actualy code is :
          MethodCallExpr nameMethod = cu.findAll(MethodCallExpr.class)
            mc.getNameAsString().equals("name") &&
            mc.getArguments().size() == 1 &&
            mc.getArgument(0).isLiteralStringValueExpr() && 
          MethodCallExpr wireClassMethod = nameMethod.findAncestor(MethodCallExpr.class, a->a.getNameAsString().equals("wireClass")).get();
          MethodCallExpr wireTypeRef = new MethodCallExpr(wireClassMethod.getScope().get(), "wireTypeReference", NodeList.nodeList(new StringLiteralExpr("test")));
It works when using PrettyPrinter but that really messes up my code so I need to preserve the lexical structure
Cameron Braid
Found it.. need to run LexicalPreservingPrinter.setup(cu) BEFORE doing mutations on the compilation unit
jean pierre Lerbscher
Hi @cameronbraid we can't help you with so little information. The least thing would be to provide a minimalist test case.
Danny van Bruggen
@gontijolucas - no response from @SmiddyPence, so I say go ahead! I'm not aware of translations. @ftomassetti is author #3 but I doubt he will protest.
@lucamolteni - I'm in the background, supporting the new team :-) --> @maartenc @jlerbsc @MysterAitch <--
@lucamolteni I bet the answer to your riddle is something about how helpful JavaParser is trying to be with literals, and how it is failing to be consistent :-)
Danny van Bruggen
@maartenc @jlerbsc @mysteraitch, @lucamolteni works on RedHat's Drools (https://www.drools.org/) which was prototyped with JavaParser, and if I'm not mistaken it is still based on it. Pretty cool if you ask me.
Federico Tomassetti
I confirm I will not protest 🙂
Damn the issue was commented 7 years ago. I feel oooold
Matthew Kramer
@matozoid Got it, thanks for the response!
Hello, I have been playing with JavaParser serialization and DotPrinter (which are very cool tools). The JSON and Dot outputs are different in terms of child order. For example, JSON prints the children of BinaryExpr as (left, operator, right) while DotPrinter print (operator, left, right). I was wondering if there is a grammar that I can follow to make these consistent with each other? Thank you.
Chinese News Board
@ftomassetti ... Do you know anything about it? Do you know what I could 'null' so that an AST is cleared from memory (Java Heap) after I'm done with a CompilationUnit generated by StaticJavaParser ???
As I explained, I parse around 330 '.java' source-code files with JP - to extract source-code for code-hiliting in a JavaDoc HTML Extention Tool - it works fine - but memory heap grows and grows. @ftomassetti ...
jean pierre Lerbscher
@ralphcnb_twitter perhaps you can do a PhantomNodeLogic.cleanUpCache() to limit memory footprint.
Chinese News Board

Hey, thanks, just got back. I will try that. All I know is that after using an AST to retrieve stuff (String's), if I try to do something like ...

.forEach((Node nChild) -> 
            { try { nChild.removeForced(); ...

It starts throwing exceptions. It seems like this could be a trivial operation I'm trying to do, but I cannot figure it out. Thanks for the advice, will try later today. For System.gc() to actually do its magic, the references have to be null...

Chinese News Board

I read through it, and it looked like the light at the end of the tunnel for me! I wasn't aware that there was a cache in LexicalPreservingPrinter ... I get this exception:

Torello/HTML/Tools/JavaDoc/JavaSourceCodeFile.java:30: error: 
PhantomNodeLogic is not public in com.github.javaparser.printer.lexicalpreservation; cannot be accessed from outside package
import com.github.javaparser.printer.lexicalpreservation.PhantomNodeLogic;
Torello/HTML/Tools/JavaDoc/JavaSourceCodeFile.java:449: error: 
PhantomNodeLogic is not public in com.github.javaparser.printer.lexicalpreservation; cannot be accessed from outside package
2 errors

Is there any chance I'm using an "older" jar file? If that's the source of what "feels like" a memory-leak, is there a newer JP JAR File that I would need? I have been using (for almost a year now)
javaparser-core-3.14.159265359.jar This looks very promising...

Chinese News Board
According to this Java-Parser JavaDoc Site https://www.javadoc.io/doc/com.github.javaparser/javaparser-core/latest/index.html
It says that both PhantomNodeLogic is a public class, and that cleanUpCache() is a public static method, so I couldn't really be able to say why my JDK is reporting that it isn't public so... If anyone knows the answer... I don't have a GitHub account, and haven't ever built JP before, would I have to do that or something?
jean pierre Lerbscher
@ralphcnb_twitter you are using an old JP version. Try the lastest version 3.16.2.
Chinese News Board

Thanks!!! It worked... BTW, I wrote my own build tool for my library - it's not Maven or Gradle (It's this very large Java Package), so I just kept using the JP Jar I got off the Internet... It has always worked though... I got 3.16.2 (It's 6:50 AM right now, here in Dallas)...

Free Memory Available:             242,205,208
Total Memory Available:            255,524,864
Loading File:                      javadoc/Torello/Languages/Verbs.WebFiles.html
Fully-Qualified Name:              Torello.Languages.Verbs.WebFiles
Built from Source-File:            Torello/Languages/Verbs.java
Relative-URL String:               ../../
Parsed JavaDoc '.html':            Name [Verbs.WebFiles], Package [Torello.Languages], CIET [class]
Parsed Source '.java':             Name [Verbs.WebFiles], Package [Torello.Languages], CIET [class]
'.html' File Parser Found:         [000] Fields, [000] Constructors, [004] Methods
'.java' File, JavaParser Found:    [000] Fields, [001] Constructors, [004] Methods

The garbage collector seems to have got it all... Thanks Mr. Lerbscher ... I know you mentioned LexicalPreservingPrinter being the source of it, but I didn't quite get it...

This is what it used to look like.... At the end of the build...
Free Memory Available:             315,115,776
Total Memory Available:            709,603,328
It would get slower and slower
Chinese News Board
HEY!!! I took the train to Fort Worth (Texas) this morning. It's Halloween... I brought my laptop. I'm at Starbucks. Happy Halloween. Great stress relief after all the "Brain control" and staring at how to fix my Java Parser segment of my program! It worked! Fort Worth Water Gardens
Danny van Bruggen
Good to hear, nice pic!


I am trying to write a piece of code that removes useless empty if-else statements from code. For example...

if (true) { } else { }

but I seem to be running into an issue which I am not sure if it is just me missing something, or whether it is a bug.

My code is as follows:

class EmptyIfVisitor : VoidVisitorAdapter<Unit>() {
    override fun visit(ifStmt: IfStmt, arg: Unit?) {
        super.visit(ifStmt, arg)
        val condition = simplifyExpr(ifStmt.condition)
        val thenStmt = ifStmt.thenStmt
        val elseStmt = ifStmt.elseStmt.orElse(null)

        if (condition is BooleanLiteralExpr) {
            if (isEmptyStatement(thenStmt) && isEmptyStatement(elseStmt)) {
                // We can happily remove this block, as it is doing absolutely nothing useful whatsoever.
                logger.warn { "removing useless ${debugString(ifStmt, verbose = true)}" }

however, the ifStmt.remove() is currently throwing a ConcurrentModificationException whenever it is hit, assumably because it is modifying the internal NodeList on the parent while iterating over it.

Is there some way to do what I want to do? The only other solution is to do ifStmt.replace(EmptyStmt()) but that really feels like a bodge to me.

stack trace is
    at java.util.ArrayList.forEach(ArrayList.java:1262)
    at com.github.javaparser.ast.NodeList.forEach(NodeList.java:290)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.visit(VoidVisitorAdapter.java:109)
    at com.github.javaparser.ast.stmt.BlockStmt.accept(BlockStmt.java:76)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.lambda$visit$104(VoidVisitorAdapter.java:369)
    at java.util.Optional.ifPresent(Optional.java:159)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.visit(VoidVisitorAdapter.java:369)
    at com.github.javaparser.ast.body.MethodDeclaration.accept(MethodDeclaration.java:106)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.lambda$visit$31(VoidVisitorAdapter.java:154)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at com.github.javaparser.ast.NodeList.forEach(NodeList.java:290)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.visit(VoidVisitorAdapter.java:154)
    at com.github.javaparser.ast.body.ClassOrInterfaceDeclaration.accept(ClassOrInterfaceDeclaration.java:100)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.lambda$visit$43(VoidVisitorAdapter.java:175)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at com.github.javaparser.ast.NodeList.forEach(NodeList.java:290)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.visit(VoidVisitorAdapter.java:175)
    at com.github.javaparser.ast.CompilationUnit.accept(CompilationUnit.java:134)
    at <my unit test that calls CompilationUnit#accept(EmptyIfVisitor(), null)>
    at <other junit stuff>
jean pierre Lerbscher
hi @ascopes because you modify the AST you can use a ModifierVisitor like this
ModifierVisitor v = new ModifierVisitor<Void>() {
        public Visitable visit(IfStmt ifs, Void arg) {
            return null;   
    v.visit(cu, null);
ah awesome, thanks
Danny van Bruggen
Also the functional traversal style has protection built in against that: https://javaparser.org/functional-tree-traversal/
Amartya Vats
I am trying to write a piece of code through which I can print all the methods that have been called in a constructor. For a non contructor method it is easy to do with MethodCallExpr, how to do the same for a constructor?
and check the class it extends from.
Hello, I have been testing JavaParser against the JDK's own code and have some issues. What is the best way for me to report them?
Sorry - forget it. I found the info I needed.
Danny van Bruggen
Well, that's quick :-)
I'm curious what that info was though (setting the language level maybe?)
Cheikh Saadbouh

hello everyone i am new to javaParser and i need some help .

i want :

  • delete some method parameters
  • replace statement A with statement B
class MethodChangerVisitor extends VoidVisitorAdapter<Void> {
    public   void visit(MethodDeclaration n, Void arg) {

          System.out.println(n.getParameters().remove(0));//remove parameter not working
          //replace statement with other statement ?
          System.out.println(n.getBody().get().getStatements().get(0).asExpressionStmt().setExpression("int a = 5;"));

        super.visit(n, arg);
jean pierre Lerbscher
Hi @cheikh-sadbouh why do you say "n.getParameters().remove(0)" doesn't work? Do you have an exception?
12 replies


I have a question about chained method calls.
Given a chained invocation (builder pattern):

return new ThingBuilder().withA(a).withB(b).build();

How can I use JavaParser to add another chained invocation to end up with code like this:

return new ThingBuilder().withA(a).withB(b).withC(c).build();

Inserting it anywhere in the chain (before build()) is fine.

15 replies
does anyone know of a Language Server Protocol impl, that can be driven from a JavaCC grammar?
3 replies
Yevgen Muntyan

Good morning. I am using LexicalPreservingPrinter to do some code modifications, and it works well, but I can't figure out how to insert whitespace where I need it. My goal is to replace code like

    function(new RuntimeException("abc"),


    new RuntimeException("abc",

But I can't get the newlines in the replacement, I can only get

    new RuntimeException("abc", anArgument, anotherArgument);

Is it possible to do what I want?

12 replies
Roger Howell
v3.17.0 released -- it'll be available as soon as bintray/sonatype/maven central do their thing!