Run a method before and after a called method in J

2019-06-15 15:06发布

问题:

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.

回答1:

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.



回答2:

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.