Is it possible to get an instance of an object that calls a method using AspectJ?

Imagine the following aspect:

aspect FaultHandler { pointcut services(Server s): target(s) && call(public * *(..)); before(Server s): services(s) { // How to retrieve the calling object instance? if (s.disabled) ...; } } 

A point reference captures all calls to public Server methods and launches the before just before calling any of them.

Is it possible to get an instance of an object that calls the public Server method in the before board? If so, how?

+6
source share
1 answer

you can use this () pointcut:

 pointcut services(Server s, Object o) : target(s) && this(o) && call.... 

Obviously, you can use a specific type instead of Object if you need to span it.

EDIT

You can also use the thisJoinPoint variable:

 Object o = thisJoinPoint.getThis(); 

Using this JoinPoint method often results in small performance penalties compared to using certain pointcuts; it can be used if the calling object is a static class.

In this case, there is no "this", so this (o) may not match, and thisJoinPoint.getThis () returns null.

However, using:

 Class c = thisEnclosingJoinPointStaticPart.getSignature().getDeclaringType(); 

Will tell you a class containing a static method. Examining more signature fields may also give you a method name, etc.

+4
source

Source: https://habr.com/ru/post/896907/


All Articles