我想在 java 中通过注解注入(inject)一些代码。 计划是我有两个方法 beginAction() 和 endAction()。我想注释一个方法,以便在执行方法中的语句之前放置 beginAction() 并在完成执行后自动放置 endAction() 。是否可以。如果是,请建议我该怎么做。
@MyAnnotation
public void myMethod(){
// Statement 1;
// Statement 2;
}
在运行时,应该通过注释将 beginAction() 和 endAction() 注入(inject)到方法中。那就是它在运行时应该变成像下面这样。
public void myMethod{
beginAction();
// Statement 1;
// Statement 2;
endAction();
}
最佳答案
看起来你需要方面。在这种情况下,AspectJ 是最受欢迎的库。您可以在这里阅读更多相关信息:https://eclipse.org/aspectj/docs.php
下面是使用此类方面的示例:
带有拦截方法的类:
public class YourClass {
public void yourMethod() {
// Method's code
}
}
方面本身:
@Aspect
public class LoggingAspect {
@Around("execution(* your.package.YourClass.yourMethod(..))")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Do something before YourClass.yourMethod");
joinPoint.proceed(); //continue on the intercepted method
System.out.println("Do something after YourClass.yourMethod");
}
}
关于java - 是否可以通过注解在特定位置注入(inject)代码行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34790952/