【问题标题】:access class variable in aspect class访问方面类中的类变量
【发布时间】:2011-12-10 18:56:39
【问题描述】:

我正在使用 spring aspectj 创建一个方面类,如下所示

@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;
    }

} 

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

我的 abc 类如下

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");
}
}

如何访问方面类中的名称?

【问题讨论】:

    标签: java spring jakarta-ee aspectj spring-aop


    【解决方案1】:

    您需要获取对目标对象的引用并将其强制转换为您的类(也许在instanceof 检查之后):

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

    推荐的方法(为了性能和类型安全)是在切入点中提到目标:

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

    但这只会匹配对 Abc 类型目标的执行。

    【讨论】:

      【解决方案2】:

      @Hemant

      您可以从 ProceedingJointPoint 对象访问声明类型及其字段,如下所示:

      @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());
          }
          ...
      }
      

      字段和方法是 java.lang.reflect 包的一部分

      【讨论】:

        【解决方案3】:

        如果您使用的是 Spring,那么您可以使用 AOPUtils 辅助类

         public Object invoke(MethodInvocation invocation) throws Throwable
         {
              Class<?> targetClass = AopUtils.getTargetClass(invocation.getThis())
         }
        

        【讨论】:

          猜你喜欢
          • 2013-09-08
          • 2023-04-01
          • 2017-08-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-28
          • 2011-09-05
          相关资源
          最近更新 更多