Matt
Matt

Reputation: 11327

Run extra code for any method in a class

I have some code I want to run every time any method is invoked in a specific Java class, but don't want to touch the actual method bodies. This is because there are a lot of methods that change frequently, and the people programming these methods shouldn't have to worry about adding my code to every method.. even if it is just a single line that calls another method.

I can't think of a way to achieve this with inheritance, so I was wondering if it is possible with reflection? Or even at all?

It's possible to get a list of methods in a class, inspect their properties and even invoke them. But I'm not seeing anything that lets you attach extra code, such as an event handler for example. Maybe Java is the wrong language for something like this..

Upvotes: 2

Views: 571

Answers (2)

dharam
dharam

Reputation: 8106

This is very common behavior, where Aspect Oriented Programming is definitely the right thing to use.

But I also get impressed with how the famous CMS does it.

For each class which contains the concrete method around, you can have a property (List of methods) which contains the code you want to execute before the method call.

You can write a registerBeforeCall(Method m) method which takes a method and adds to teh list.

Your method should contain a for loop at the first line(which goes through the list of methods) and invoke each of the method one by one.

Do not forget to put a try and catch and ignore the exception if there is any in the invocations.

For e.g. :

public void myActualMethod(){
    for(Method m : registeredMethodsToCallBeforeActualCode){
        m.invoke();
    }

    //my actual code

    // here you can also write a for loop to execute all the methods which you want to call after your actual code is executed.

}

This approach is not very special, but is widely use, when you do not choose AOP.

Upvotes: 1

AppX
AppX

Reputation: 528

one way to implement it by inheritance is:

    public SuperClass {

       public void doSomething() {
          doBefore();
          doSpecific();
          doAfter();
       }

       protected abstract void doSpecific();

    }

    public SubClass extends SuperClass {
       protected void doSpecific() {
          System.out.println("Do specific implementation....");
       }
    }


public static void main(String[] args) {
   SuperClass clazz = new SubClass();
   clazz.doSomething();
}

Upvotes: 0

Related Questions