1

I've got the MethodCallExpr and FieldAccessExpr from each method. Here is some code I've done.

for (TypeDeclaration<?> typeDec : cu.getTypes()) {
        for (MethodDeclaration method : typeDec.getMethods()) {
            method.getBody().ifPresent(field -> {
                System.out.println(ml.getMethodsByClass(0,methodCol));
                System.out.println("Method call : " + field.findAll(MethodCallExpr.class));
                //stmtMethod = field.findAll(MethodCallExpr.class);
                System.out.println("Field access : " + field.findAll(FieldAccessExpr.class));
                //stmtVariables = field.findAll(FieldAccessExpr.class);
            });
            methodCol++;
            System.out.println();
        }
    }

CAUSE: I'm not able to get the name of the MethodAccessExpr and FieldAccessExpr.

Actual output:

methodC
ethod calls : [d1.methodA(), d1.methodB(), System.out.println(d1.text1 + "\t" + d1.text2)]
field access : [System.out, d1.text1, d1.text2]<br>
methodD
method calls : [d3.methodE(), System.out.println(d3.d3x + "\t" + d3.d3y)]
field access : [System.out, d3.d3x, d3.d3y]

Expected Output:

methodC
method calls: methodA, methodB, println
field access: out, text1, text2
methodD
method calls: methodE, out
field access: out, d3x, d3y
ardant
  • 23
  • 6

1 Answers1

2

You're almost there. The only problem I see is that findAll returns a list, and you use this list as argument to System.out. What you need to do is retrieve each element in the list to get its name. Here is a sample (note that I've renamed field to blockStatement for consistency):

for (TypeDeclaration<?> typeDec : cu.getResult().get().getTypes()) {
    for (MethodDeclaration method : typeDec.getMethods()) {
        method.getBody().ifPresent(blockStatement -> {
            List<FieldAccessExpr> results = blockStatement.findAll(FieldAccessExpr.class);
                for( FieldAccessExpr expr : results ) {
                    System.out.println(expr.getName());
                }

If you just want to print all the fields (and method) names, a more compact way is using streams:

blockStatement.findAll(FieldAccessExpr.class)
    .stream()
    .map(FieldAccessExpr::getName)
    .forEach(System.out::println);
SDJ
  • 4,083
  • 1
  • 17
  • 35