是否可以通过注释

时间:2016-01-14 13:32:16

标签: java annotations

我想通过java中的注释注入一些代码。 计划是我有两个方法beginAction()和endAction()。我想注释一个方法,这样在执行方法中的语句之前,将放置beginAction(),在完成执行后,endAction()将自动放入。可能吗。如果是,请建议我该怎么做。

@MyAnnotation
public void myMethod(){
    // Statement 1;
    // Statement 2;
}

在运行时,应通过注释在方法中注入beginAction()和endAction()。那就是它应该在运行时变得像以下那样。

public void myMethod{
    beginAction();
    // Statement 1;
    // Statement 2;
    endAction();
}

2 个答案:

答案 0 :(得分:1)

看起来你需要方面。在这种情况下,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");
   }

}

答案 1 :(得分:0)

你不能只使用普通的Java来做到这一点。但是,有一种类似Java的语言可以实现这一点。它被称为Xtend。它编译为Java,而不是字节码,因此它受益于Java编译器所做的所有精彩事情。

它始于Eclipse项目,但现在也可用于IntelliJ。

其众多功能之一是名为" Active Annotations"。它们完全符合您的要求:它们允许您参与代码生成过程,因此您可以根据需要插入beginAction()endAction()方法。

有关Active Annotations的详细信息,请参阅http://www.eclipse.org/xtend/documentation/204_activeannotations.html

相关问题