Java method call parser?
I need to resolve some method calls, including the entire signature in some Java classes, for example:
public class MyClass { public void myMthod() { // ... some code here result = someInstance.someOtherMethod(param1,param2); // ... some other code here } }
As a result, I want something similar:
serviceName = someInstance methodName = someOtherMethod arguments = { argument = java.lang.String,argument = boolean } result = java.lang.Long
What is the quickest way to achieve this goal? I'm thinking about using regex parser The problem is that there are several modes of occurrence, such as
a) result = someInstance.someOtherMethod(getSomething(),param); b) result = getSomeInstance().someOtherMethod(param); c) result = getSomeInstance() .someOtherMethod( getSomethingElse(),null,param);
Any help will be appreciated! thank you!
Solution
Do not use regular expressions! Use tools to understand java
use:
>Source code parser (such as javaparser) > bytecode analysis (such as ASM) > one aspect (AspectJ)
In the source parser and ASM, you will write a visitor to scan method calls
For javaparser: read this page, extend the voidvisitoradapter and overwrite it
public void visit(MethodCallExpr n,A arg)
Example code:
public static void main(final String[] args) throws Exception{ parseCompilationUnit(new File("src/main/java/foo/bar/Phleem.java")); } public static void parseCompilationUnit(final File sourceFile) throws ParseException,IOException{ final CompilationUnit cu = JavaParser.parse(sourceFile); cu.accept(new VoidVisitorAdapter<Void>(){ @Override public void visit(final MethodCallExpr n,final Void arg){ System.out.println(n); super.visit(n,arg); } },null); }
The problem here is that you only have the object name, not the object type, so you must also keep a local variable / field map to type, which is where things get messy After all, ASM may be an easier choice
For ASM: read this tutorial page to get started