在 Java 中的被调用方法之前和之后运行一个方法 [英] Run a method before and after a called method in Java

查看:57
本文介绍了在 Java 中的被调用方法之前和之后运行一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 Java 程序,以便在调用 methodA() 后,首先调用名为 methodBeforeA() 的方法,然后调用 methodA() 被执行,然后是另一个名为 methodAfterA() 的方法.这与 Junit 使用注释(使用@Before、@Test、@After)所做的非常相似,所以我认为使用反射应该是可能的,但我没有很好的线索.

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.

推荐答案

AspectJ 允许您在方法进入之前和方法退出之后指定切点.

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

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

在 AspectJ 中,切入点挑选出程序流中的某些连接点.例如,切入点

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

call(void Point.setX(int))

挑选出每一个调用具有签名void Point.setX(int)——即Point的方法的连接点带有单个 int 参数的 void setX 方法.

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.

这篇关于在 Java 中的被调用方法之前和之后运行一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆