Javaparser: Modify a VariableDeclarationExpr's righthand side to be null

Created on 26 Dec 2016  路  4Comments  路  Source: javaparser/javaparser

If I have a VariableDeclarationExpr such as:

VariableDeclarationExpr aExpr = (VariableDeclarationExpr) exp;

where the expression is something like:

Type obj = new Type(baz);

or

Type obj = foo.m(bar);

How can I modify aExpr such that the resulting expression is:

Type obj = null;

Question (JP usage)

All 4 comments

null is represented by a NullLiteralExpr. So you want to get the declaration and do setInitialization(new NullLiteralExpr())

Thanks for the solution! The way that I've implemented this is as follows:

VariableDeclarationExpr vdExpr = (VariableDeclarationExpr) exp;
VariableDeclarationExpr exprCopy = (VariableDeclarationExpr) vdExpr.clone();

List<VariableDeclarator> vars = exprCopy.getVariables();
VariableDeclarator vd = vars.get(0);

Type type = exprCopy.getElementType();
if (primitives.contains(type.toString())) {
    // Set right hand side to calculated value/zero value
    vd.setInitializer(new IntegerLiteralExpr("0"));
} else {
    // Set right hand side to null
    vd.setInitializer(new NullLiteralExpr());
}
ExpressionStmt newStmt = new ExpressionStmt(exprCopy);
exprCopy.setParentNode(newStmt);
statements.add(i, newStmt);

Is this good style? I am wondering specifically about grabbing the VariableDeclarator from the expression with the statement vars.get(0). Can I be certain that it'll always be the first element within the list? And what is an example of a VariableDeclarationExpr with more than one VariableDeclarator when I call getVariables()?

This is a variable declaration of more than one variable:

int a=4, b=6;

so to make rock solid code, you would want your algorithm to go through all the variables, which is not much more work.

With a few more tweaks, we get this:

        VariableDeclarationExpr vdExpr = (VariableDeclarationExpr) exp;
        VariableDeclarationExpr exprCopy = (VariableDeclarationExpr) vdExpr.clone();

        for(VariableDeclarator vd: exprCopy.getVariables()) {
            Type type = exprCopy.getElementType();
            if (type instanceof PrimitiveType) {
                // Set right hand side to calculated value/zero value
                vd.setInitializer(new IntegerLiteralExpr("0"));
            } else {
                // Set right hand side to null
                vd.setInitializer(new NullLiteralExpr());
            }
        }

        ExpressionStmt newStmt = new ExpressionStmt(exprCopy);

(this is assuming the latest version of the library, by the way)

Thank you for the clarification and explanation!

Was this page helpful?
0 / 5 - 0 ratings