首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在方面构造函数中获取切入点细节

如何在方面构造函数中获取切入点细节
EN

Stack Overflow用户
提问于 2015-06-13 19:24:05
回答 1查看 237关注 0票数 1

我有一个注释风格的方面,大概是这样的:

代码语言:javascript
复制
//....
//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)来捕获这个对象,但这并没有起到任何作用。我还尝试在构造函数中引入一个参数,但这导致了一个错误。

EN

回答 1

Stack Overflow用户

发布于 2015-06-28 06:38:26

实际上,在构造函数中不需要做任何事情。您只需在percflow()中将切入点声明为独立对象,并在percflow()@Before通知中使用它,正如实例化模型所暗示的那样,该通知将只执行一次,并通过相应的JoinPoint对象为您提供所有必要的信息。现在,您可以随心所欲地记录或存储信息。

顺便说一句,使用构造函数的想法不是很好,因为在构造函数中,方面实例还没有初始化(hen和egg问题),并且在试图访问它时会导致异常。

代码语言:javascript
复制
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 {}
代码语言:javascript
复制
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 ");
    }
}
代码语言:javascript
复制
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);
    }
}

控制台输出:

代码语言:javascript
复制
execution(String de.scrum_master.app.Application.repeatText(int, String))
  repeatText
    3
    andale 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30818113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档