java – 在方面类中访问类变量

前端之家收集整理的这篇文章主要介绍了java – 在方面类中访问类变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在创建一个带有spring aspectj的方面类,如下所示

  1. @Aspect
  2. public class AspectDemo {
  3. @Pointcut("execution(* abc.execute(..))")
  4. public void executeMethods() { }
  5. @Around("executeMethods()")
  6. public Object profile(ProceedingJoinPoint pjp) throws Throwable {
  7. System.out.println("Going to call the method.");
  8. Object output = pjp.proceed();
  9. System.out.println("Method execution completed.");
  10. return output;
  11. }
  12. }

现在我想访问类abc的属性名称然后如何在方面类中访问它?
我想在profile方法显示abc类的name属性

我的abc课程如下

  1. public class abc{
  2. String name;
  3. public void setName(String n){
  4. name=n;
  5. }
  6. public String getName(){
  7. return name;
  8. }
  9. public void execute(){
  10. System.out.println("i am executing");
  11. }
  12. }

如何访问方面类中的名称

最佳答案
您需要获取对目标对象的引用并将其强制转换为您的类(在执行checkof之后):

  1. Object target = pjp.getTarget();
  2. if (target instanceof Abc) {
  3. String name = ((Abc) target).getName();
  4. // ...
  5. }

建议的方法(性能和类型安全)是指切入点中提到的目标:

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

但这只会匹配Abc类型目标的执行情况.

猜你在找的Spring相关文章