Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method invocation parser?

Tags:

java

parsing

I need to parse certain method invocation calls including the whole signature out of some Java classes, e.g.

public class MyClass {
    public void myMthod() {
        // ... some code here
        result = someInstance.someOtherMethod(param1, param2);
        // ... some other code here
    }
}

As a result I would like to get something like:

serviceName = someInstance
methodName = someOtherMethod
arguments = {
   argument = java.lang.String,
   argument = boolean
}
result = java.lang.Long

What would be the fastest way to achieve this? I was thinking about using a RegEx parser. The problem there is there are several occurence patterns, e.g.

a)
result = someInstance.someOtherMethod(getSomething(), param);

b)
result = 
    getSomeInstance().someOtherMethod(param);

c)
result = getSomeInstance()
            .someOtherMethod(
                    getSomethingElse(), null, param);

Any help would be really appreciated! Thanks!

like image 854
Peter Avatar asked May 13 '26 13:05

Peter


1 Answers

Don't use regex! Use tools that understand java.

Use either:

  • A source code parser (e.g. javaparser)
  • Byte code analysis (e.g. ASM)
  • An aspect (AspectJ)

In both source parser and ASM, you will write a visitor that scans for method invocations.


For javaparser: Read this page, extend VoidVisitorAdapter and override

public void visit(MethodCallExpr n, A arg)

Sample 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 names, not the object types, so you will also have to keep a local Map of variable / field to type and that's where things get messy. Perhaps ASM is the easier choice, after all.


For ASM: read this tutorial page to get started

like image 194
Sean Patrick Floyd Avatar answered May 16 '26 03:05

Sean Patrick Floyd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!