Search code examples
javaparsingantlrjavaparser

Change method level String variables with JavaParser


I want to use JavaParser in order to change all String variable values in a Java source code from any value to "".

I can change the value of the global variables, but I cannot manage to change the value of the method level variables.

Looking around, I got help from this and this answers and now I can get the value of every line of code in each method, like so:

static void removeStrings(CompilationUnit cu) {
        for (TypeDeclaration typeDec : cu.getTypes()) {
            List<BodyDeclaration> members = typeDec.getMembers();
            if (members != null) {
                for (BodyDeclaration member : members) {
                    if (member.isMethodDeclaration()) {                                                  // If it is a method variable
                        MethodDeclaration method = (MethodDeclaration) member;
                        Optional<BlockStmt> block = method.getBody();
                        NodeList<Statement> statements = block.get().getStatements();

                        for (Statement tmp : statements) {
                            // How do I change the values here?
                        }

                    }
                }
            }
        }
    }

Now, how do I change the values of tmp if it is a String declaration?


Solution

  • Do you mean like this?

    static void removeStrings(CompilationUnit cu) {
        cu.walk(StringLiteralExpr.class, e -> e.setString(""));
    }
    

    Test

    CompilationUnit code = JavaParser.parse(
            "class Test {\n" +
                "private static final String CONST = \"This is a constant\";\n" +
                "public static void main(String[] args) {\n" +
                    "System.out.println(\"Hello: \" + CONST);" +
                "}\n" +
            "}"
    );
    System.out.println("BEFORE:");
    System.out.println(code);
    
    removeStrings(code);
    
    System.out.println("AFTER:");
    System.out.println(code);
    

    Output

    BEFORE:
    class Test {
    
        private static final String CONST = "This is a constant";
    
        public static void main(String[] args) {
            System.out.println("Hello: " + CONST);
        }
    }
    
    AFTER:
    class Test {
    
        private static final String CONST = "";
    
        public static void main(String[] args) {
            System.out.println("" + CONST);
        }
    }