2

I am working on a program where I need to be able to check when certain methods are run on a particular object. I know that's probably a bit unclear, so here's an example.

Let's say that this is the class I am trying to access:

public class Clazz {

    public void exampleMethod(ExampleParam param) {
        //Unknown code
    }
}
  1. The Clazz object is not created by any of my code. I have no control over its creation.
  2. The methods of Clazz (in this example, just exampleMethod(ExampleParam param)) are not called by any of my code.

What I need to do is have a way to determine when exampleMethod(ExampleParam param) is called by code that I do not have access to.

The code that is run inside the method is irrelevant to me. All I need to know is:

  1. Every time the method is called.
  2. If possible, the parameters that were passed into the method.
  3. If on the off chance that the above is possible, it would also be useful to know the class that originally called the method.

In other words, is it possible to create a "method called" listener?

user3144349
  • 419
  • 1
  • 4
  • 12
  • The only thing I see is to create proxy objects. But you will need to manage all the instanciation of all your object, and I don't think you want to do that. That's pretty hard to do. You can look at http://stackoverflow.com/questions/4777050/how-to-create-proxy-in-java . – lpratlong May 20 '14 at 19:05
  • @Ipratlong: What do you mean by a proxy object? I'm sorry, I've never heard of that concept before. EDIT: Thank you. – user3144349 May 20 '14 at 19:07
  • Aspects are your friend. See http://elope.wordpress.com/2007/09/26/tutorial-profiling-with-aspectj/ – Dirk Lachowski May 20 '14 at 19:07
  • You totally can do this. Use or implement your own AOP. At a basic level you can rewrite (at run time) the method calls that you want to monitor to call your stuff before (or after) executing. – DwB May 20 '14 at 19:07
  • Maybe the [Observer-Pattern](http://en.wikipedia.org/wiki/Observer_pattern) can help you, but I can't fully grasp your requirements. – Alexander_Winter May 20 '14 at 19:07
  • @DirkLachowski is right. Look at AOP, it will be easier. – lpratlong May 20 '14 at 19:07
  • Just a thought, "instrumentation" like done by Cobertura is one way to achieve this. – Sangharsh May 20 '14 at 19:33

1 Answers1

3

In Java, this is handled by "Aspect Oriented Programming" (also known as AOP).

AOP is included as part of the core spring framework, check there for more info.

DwB
  • 37,124
  • 11
  • 56
  • 82
  • Thank you! I am going to look at AOP now to make sure it is what I need, then I will report back with an update. – user3144349 May 20 '14 at 19:12