fields in the method

81 views
Skip to first unread message

Aatira Anum FAST-NU

unread,
Oct 4, 2009, 8:05:03 AM10/4/09
to JavaParser
I want to get the fields in the method. For example

class A
{
int x;
int y;
public int getSum(){
return x+y;
}

public int getX(){
return x;
}

}

I want to return the answer that the getSum() method uses the variable
x and y and the getX() method uses the variable x.

MariuszF

unread,
Oct 4, 2009, 9:26:23 AM10/4/09
to JavaParser
I think we need to use a visitor to search for variables. This will be
the easiest solution.

PS: please use the same thread for posting new messages :)

MariuszF

unread,
Oct 4, 2009, 9:46:46 AM10/4/09
to JavaParser
import japa.parser.JavaParser;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.expr.NameExpr;
import japa.parser.ast.visitor.VoidVisitorAdapter;

import java.io.FileInputStream;


public class ClassVisitor {

public static void main(String[] args) throws Exception {
// creates an input stream for the file to be parsed
FileInputStream in = new FileInputStream("c://test");

CompilationUnit cu;
try {
// parse the file
cu = JavaParser.parse(in);
} finally {
in.close();
}

// visit and print the methods names
new MethodVisitor().visit(cu, null);
}

private static class MethodVisitor extends VoidVisitorAdapter {

@Override
public void visit(MethodDeclaration n, Object arg) {
System.out.println("Method name: "+n.getName());
visit(n.getBody(), arg);
}

public void visit(NameExpr ne, Object o){
System.out.println(ne.getName());
}
}
}


output:
Method name: getSum
x
y
Method name: getX
x

Jasmeet

unread,
Nov 26, 2012, 10:29:02 PM11/26/12
to javap...@googlegroups.com
Hey that was great. That helped me a lot with my research. Could you help a bit more? I am trying to parse a method and find the number of times a variable is read, written or non-deterministically used(as in we can not be sure if it was read or written).

Is there a documentation on this wonderful project?? I really appreciate your work. 
Reply all
Reply to author
Forward
0 new messages