Run a method before and after a called method in Java

放肆的年华 提交于 2020-01-03 07:23:32

问题


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.



来源:https://stackoverflow.com/questions/9596991/run-a-method-before-and-after-a-called-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!