我有一个注释样式方面,就像那样:
//....
//somewhere in another class
//
@MyAnnotation
public void foo(){ \* does stuff *\}
/////////////////////
// in the aspect file
@Aspect("percflow(execution(@com.bla.MyAnnotation * *(..)))")
public class MyAspect {
public MyAspect(){
/* Here I'd like to access the name of the annotated function e.g: foo*/
}
/* more pointcuts and advice*/
}
我尝试使用this(Object)
捕获对象,但这并没有任何好处。
我也试过在构造函数中引入一个参数,但这只会导致错误。
答案 0 :(得分:0)
嗯,实际上没有必要在构造函数中做任何事情。您可以将percflow()
中的切入点声明为独立对象,并在percflow()
内以及@Before
建议中使用它,正如实例化模型所暗示的那样,只会执行一次,通过相应的JoinPoint
对象为您提供所有必要的信息。您现在可以按照自己的喜好记录或存储信息。
package de.scrum_master.app;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {}
package de.scrum_master.app;
public class Application {
public void doSomething() {}
@MyAnnotation
public String repeatText(int times, String text) {
String result = "";
for (int i = 0; i < times; i++)
result += text;
return result;
}
public static void main(String[] args) {
Application application = new Application();
application.doSomething();
application.repeatText(3, "andale ");
}
}
package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect("percflow(myPointcut())")
public class MyAspect {
@Pointcut("execution(@de.scrum_master.app.MyAnnotation * *(..))")
private static void myPointcut() {}
@Before("myPointcut()")
public void myAdvice(JoinPoint thisJoinPoint) {
System.out.println(thisJoinPoint);
System.out.println(" " + thisJoinPoint.getSignature().getName());
for (Object arg : thisJoinPoint.getArgs())
System.out.println(" " + arg);
}
}
控制台输出:
execution(String de.scrum_master.app.Application.repeatText(int, String))
repeatText
3
andale