What you are trying to do is called static code analysis - in particular data flow analysis, but with a twist ... you didnβt show, you look at the source code, but at the compiled code ... if you want to do it at runtime, where you have to deal with compiled (bytecode) code instead of the source. So, you are looking for a library capable of analyzing a bytecode data stream. There are many libraries for help (now that you know what to look for, you can find alternatives to my recommendation if you want).
OK, before reaching the example ... I like javassist - I think this is as clear as a bytecode library with great examples and documentation on the Internet. javassit has some higher level bytecode parsing API , so you donβt even have to dig too deep, depending on what you need to do.
To print the output for your Foo / Bar example, use the following code:
public static void main (String... args) throws Exception { Analyzer a = new Analyzer(); ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.get("test.Foo"); for (CtMethod cm : cc.getDeclaredMethods()) { Frame[] frames = a.analyze(cm); for (Frame f : frames) { System.out.println(f); } } }
will print:
locals = [test.Foo, int, test.Bar] stack = [] locals = [test.Foo, int, test.Bar] stack = [int] locals = [test.Foo, int, test.Bar] stack = [int, int] null null locals = [test.Foo, int, test.Bar] stack = [] locals = [test.Foo, int, test.Bar] stack = [test.Bar] null null locals = [test.Foo, int, test.Bar] stack = []
If you need more details, you will really need to read the bytecode and the JVM specification :
public static void main (String... args) throws Exception { ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.get("test.Foo"); for (CtMethod cm : cc.getDeclaredMethods()) { MethodInfo mi = cm.getMethodInfo(); CodeAttribute ca = mi.getCodeAttribute(); CodeIterator ci = ca.iterator(); while (ci.hasNext()) { int index = ci.next(); int op = ci.byteAt(index); switch (op) { case Opcode.INVOKEVIRTUAL: System.out.println("virutal");
Hope this helps you get started =)