Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a method before and after a called method in Java

I'm trying to write a Java program such that after calling a methodA(), first a method named methodBeforeA() is called and then methodA() gets executed followed by another method being called named, methodAfterA(). This is very similar to what Junit does using Annotations (using the @Before, @Test, @After), so i think it should be possible using reflection but i don't have a very good clue.

like image 871
Vanp Avatar asked Mar 07 '12 06:03

Vanp


Video Answer


2 Answers

AspectJ allows you to specify cutpoints before method entry and after method exit.

http://www.eclipse.org/aspectj/doc/released/progguide/starting-aspectj.html

In AspectJ, pointcuts pick out certain join points in the program flow. For example, the pointcut

call(void Point.setX(int))

picks out each join point that is a call to a method that has the signature void Point.setX(int) — that is, Point's void setX method with a single int parameter.

like image 183
Mike Samuel Avatar answered Oct 05 '22 07:10

Mike Samuel


This would require modifying the method code to insert calls to the other methods. Java reflection lets you do a lot of things, but it doesn't let you dynamically modify method code.

What JUnit does is different. It identifies each method annotated @Before, @Test, and @After, then does something along the lines of:

for (Method t : testMethods) {
    for (Method b : beforeMethods)
        b.invoke();
    t.invoke();
    for (Method a : afterMethods)
        a.invoke();
}

You can certainly do something like this, to make sure you call the "before" and "after" methods after every time you call the method in question. But you can't force all callers to do the same.

like image 45
Taymon Avatar answered Oct 05 '22 08:10

Taymon