views:

143

answers:

3

Hey

I'd like to know how to - if even possible - reflect what method calls are executed inside the method during execution. I'm especially interested in either external method calls (that is, methods in other classes) or calling some specific method like getDatabaseConnection().

My intention would be to monitor predefined objects' actions inside methods and execute additional code if some specific conditions are met like some method is called with specific values. The monitor would be completely external class or a set of classes with no direct access to the object to be monitored by no other way than reflection.

+1  A: 

I'd expect BCEL to be able to do this. From the web site:

The Byte Code Engineering Library is intended to give users a convenient possibility to analyze, create, and manipulate (binary) Java class files (those ending with .class).

The "analyze" part being the important bit here. The JavaDoc isn't visible on the web site (as far as I can see) so I can't easily be sure whether or not it'll help you, but it's a reasonable starting point.

Jon Skeet
+1  A: 

BCEL should offer this capability, but ...

... your requirements sound a lot like Aspect-Oriented Programming (AOP), so you should probably also look at AspectJ (with Eclipse tooling).

The main advantage of AspectJ is that it offers a well-designed way to express your specific conditions.

+2  A: 

Aspect J will solve your problem.

Try to define a pointcut like this:

pointcut profilling(): execution(public * *(..)) && (
            within(com.myPackage..*) ||

In this way you will catch all the call to any public method within the package com.myPackage. Add as many within clauses you need.

Then add the following code:

Object around(): profilling() {

    //Do wherever you need before method call
    proceed();
    //Do wherever you need after method call

}

IF you want to learn something more about aspectJ follow this guide.

sakana