访问方面类中的类变量

我正在创建一个带有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"); } } 

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

您需要获取对目标对象的引用并将其强制转换为您的类(在执行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类型的目标上的执行相匹配。

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

Field&Method是java.lang.reflect包的一部分

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

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