2016-01-14 60 views
2

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

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

在运行时,beginAction()和endAction()应在通过注释的方法进行注射。这就是它应该在运行时变得如下所示。

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

您正在寻找AspectJ。 – chrylis

+1

或弹簧拦截器;) –

+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"); 
    } 

} 
+0

感谢@Rozart的支持。 –

0

你不能用普通的Java来完成它。但是,有一种类似Java的语言允许这样做。它被称为Xtend。它编译为Java,而不是字节码,所以它受益于Java编译器所做的所有美妙的事情。

它作为一个Eclipse项目开始了生活,但现在也可用于IntelliJ。

它的许多功能之一就是所谓的“活动注释”。他们完全按照您的要求进行操作:他们允许您参与代码生成过程,因此您可以根据需要插入您的beginAction()endAction()方法。

有关活动注释的更多信息,请参阅http://www.eclipse.org/xtend/documentation/204_activeannotations.html

相关问题