access class variable in aspect class

给你一囗甜甜゛ 提交于 2019-12-18 16:47:25

问题


i am creating an aspect class with spring aspectj as follow

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

 @Around("executeMethods()")
    public Object profile(ProceedingJoinPoint pjp) throws Throwable {
            System.out.println("Going to call the method.");
            Object output = pjp.proceed();
            System.out.println("Method execution completed.");
            return output;
    }

} 

now i want to access the property name of class abc then how to acccess it in aspect class? i want to display name property of abc class in profile method

my abc class is as follow

public class abc{
String name;

public void setName(String n){
name=n;
}
public String getName(){
 return name;
}

public void execute(){
System.out.println("i am executing");
}
}

How can i access the name in aspect class?


回答1:


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.




回答2:


@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




回答3:


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())
 }


来源:https://stackoverflow.com/questions/7819410/access-class-variable-in-aspect-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!