1

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?

1 Answer 1

3

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You solved two problems (the String declarations and print's) with one line of code. I see I was complication too much. Thank you very much! Perfect solution for my problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.