我正在使用 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的属性名,那么如何在方面类中访问它呢? 我想在配置文件方法中显示 abc 类的名称属性
我的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 类型目标上的执行。
关于java - 访问方面类中的类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7819410/