A
A
Alexiuscrow2017-11-13 22:44:10
Java
Alexiuscrow, 2017-11-13 22:44:10

How to determine the method that calls the current method?

My project uses AspectJ + Spring. For all methods annotated with `@MyAnn`, you must define a class and a method (also annotated with `@MyAnn`) that calls the current method.
Example. There are 2 classes: A, B. All methods of classes A, B are annotated with `@MyAnn`. The 'firstMethod(int)' method of class A calls the `action()` method of class B. In this case, it is necessary to determine which method (annotated with `@MyAnn`) in which class calls the `action()` method of class B. Moreover, it is not enough to know method name, you need to get an object of the java.lang.reflect.Method class.

pubic class A {
    public static void main(String[] args) {
        A aClass = new A();
        aClass.firstMethod(5);
    }
    @MyAnn
    public void firstMethod() {
        System.out.println("A.firstMethod()");
        B.action();
    }
    @MyAnn
    public void firstMethod(int number) {
        System.out.println("A.firstMethod(" + number + ")");
        B.action();
    }

}
pubic class B {
    @MyAnn
    public static void action() {
        System.out.println("B.action()");
    }
}

Aspect:
@Aspect
class MyAspect {
    @Pointcut("@annotation(my.pkg.MyAnn)")
    void annotationPointCutDefinition(){}

    @Pointcut("execution(* *(..))")
    void atExecution(){}

    @Around("annotationPointCutDefinition() && atExecution()")
    Object process(ProceedingJoinPoint joinPoint) {
        // ...
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aol-nnov, 2017-11-13
@aol-nnov

https://stackoverflow.com/a/25075051

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question