access class variable in aspect class

前端 未结 3 2190
迷失自我
迷失自我 2021-01-02 12:36

i am creating an aspect class with spring aspectj as follow

@Aspect
public class AspectDemo {
  @Pointcut(\"execution(* abc.execute(..))\")
     public void          


        
相关标签:
3条回答
  • 2021-01-02 12:48

    If you are using Spring then you could use the AOPUtils helper class

     public Object invoke(MethodInvocation invocation) throws Throwable
     {
          Class<?> targetClass = AopUtils.getTargetClass(invocation.getThis())
     }
    
    0 讨论(0)
  • 2021-01-02 12:52

    You need to get a reference to the target object and cast it to your class (after an instanceof check, perhaps):

    Object target = pjp.getTarget();
    if (target instanceof Abc) {
        String name = ((Abc) target).getName();
        // ...
    }
    

    The recommended approach (for performance and type safety) is to have the target mentioned in the pointcut:

    @Around("executeMethods() && target(abc)")
    public Object profile(ProceedingJoinPoint pjp, Abc abc) ....
    

    But this will only match the executions on a target of type Abc.

    0 讨论(0)
  • 2021-01-02 12:56

    @Hemant

    You can access the declaring type and its fields from the ProceedingJointPoint object as follow:

    @Around("executeMethods()")
    public Object profile(ProceedingJoinPoint pjp) throws Throwable {
    
        Class myClass = jp.getStaticPart().getSignature().getDeclaringType();
        for (Field field : myClass.getDeclaredFields())
        {
            System.out.println(" field : "+field.getName()+" of type "+field.getType());
        }
    
        for(Method method : myClass.getDeclaredMethods())
        {
            System.out.println(" method : "+method.toString());
        }
        ...
    }
    

    Field & Method are part of the java.lang.reflect package

    0 讨论(0)
提交回复
热议问题