1

I'm trying to Parse the static variable value from the JAVA file. But couldn't be able to parse the variable.

I've used JavaParser to Parse the code and fetch the value of variable. I got success in fetching all other class level variable and value but couldn't be able to parse the static field.

The Java File looks like ...

public class ABC {
    public string variable1 = "Hello How are you?";
    public boolean variable2 = false;
    public static String variable3;
    static{
    variable3 = new String("Want to Fetch this...");
    } 
    //Can't change this file, this is input.
    public static void main(String args[]){
    //....Other Code
    } 
}

I'm able to parse the all variables value except "variabl3". The Code of Java File looks like above Java Code and I need to Parse "variable3"'s value.

I've done below code to parse the class level variable...

import java.util.HashMap;
import java.util.List;

import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;


public class StaticCollector extends 
VoidVisitorAdapter<HashMap<String, String>> {

@Override
public void visit(FieldDeclaration n, HashMap<String, String> arg) {
    // TODO Auto-generated method stub
    List <VariableDeclarator> myVars = n.getVariables();
        for (VariableDeclarator vars: myVars){
            vars.getInitializer().ifPresent(initValue -> System.out.println(initValue.toString()));
            //System.out.println("Variable Name: "+vars.getNameAsString());
            }
}

}

Main Method ...

public class Test {
public static void main(String[] args) {

    File file = new File("filePath");
    CompilationUnit compilationUnit = null;
    try {
        compilationUnit = JavaParser.parse(file);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    HashMap<String, String> collector = new HashMap<String, String>();
    compilationUnit.accept(new StaticCollector(), collector);
} 
}

How could I parse the value of "variable3", which is static and value assigned inside static block? There might be other variable in the code but I need to find value of particular variable value (in this case Variable3). Am I doing something wrong or i need to add some other way, please suggest.

Joshi Yogesh
  • 142
  • 1
  • 12

1 Answers1

0

Inspecting the AST as something that's easily readable, e.g., a DOT (GraphViz) image with PlantUML is a huge help to solve this kind of problem. See this blog on how to generate the DOT as well as other formats.

Here's the overview, with the "variable3" nodes highlighted (I just searched for it in the .dot output and put a fill color). You'll see that there are TWO spots where it occurs:

enter image description here

Zooming in on the node space on the right, we can see that the second sub-tree is under an InitializerDeclaration. Further down, it's part of an AssignExpr where the value is an ObjectCreationExpr:

enter image description here

So, I adapted your Visitor (it's an inner class to make the module self contained) and you need to override the visit(InitializerDeclaration n... method to get to where you want:

import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.InitializerDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;

public class Test {
    public static void main(String[] args) {

        File file = new File("src/main/java/ABC.java");
        CompilationUnit compilationUnit = null;
        try {
            compilationUnit = StaticJavaParser.parse(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HashMap<String, String> collector = new HashMap<String, String>();
        compilationUnit.accept(new StaticCollector(), collector);
    }

    private static class StaticCollector extends
            VoidVisitorAdapter<HashMap<String, String>> {
        @Override
        public void visit(FieldDeclaration n, HashMap<String, String> arg) {
            List<VariableDeclarator> myVars = n.getVariables();
            for (VariableDeclarator vars: myVars){
                vars.getInitializer().ifPresent(initValue -> System.out.println(initValue.toString()));
                //System.out.println("Variable Name: "+vars.getNameAsString());
            }
        }
        @Override
        public void visit(InitializerDeclaration n, HashMap<String, String> arg) {
            List<Statement> myStatements = n.getBody().getStatements();
            for (Statement s: myStatements) {
                s.ifExpressionStmt(expressionStmt -> expressionStmt.getExpression()
                        .ifAssignExpr(assignExpr -> System.out.println(assignExpr.getValue())));
            }
        }
    }
}

Here's the output showing additionally variable3's initialization in the static block:

"Hello How are you?"
false
new String("Want to Fetch this...")
Fuhrmanator
  • 11,459
  • 6
  • 62
  • 111