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?

7
  • 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 stackoverflow.com/questions/4777050/how-to-create-proxy-in-java . Commented May 20, 2014 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. Commented May 20, 2014 at 19:07
  • Aspects are your friend. See elope.wordpress.com/2007/09/26/tutorial-profiling-with-aspectj Commented May 20, 2014 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. Commented May 20, 2014 at 19:07
  • Maybe the Observer-Pattern can help you, but I can't fully grasp your requirements. Commented May 20, 2014 at 19:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.