我正在编写一个方面记录器来在访问给定类中的任何成员变量时写入日志。
如果我为下面的单个变量写一个特定的切入点,我就能得到该字段的值。
@Pointcut("get(* abc.ThreadPoolService.drMaxTh)")
public void drFields() {}
@AfterReturning(pointcut="drFields()", returning="drMaxTh")
public void afterAccessingdrFields(int drMaxTh) {
LOGGER.info("Accessed the field drMaxTh " + drMaxTh);
}
但我的班级有十几个+变量,我不打算为每个变量编写特定的切入点。所以,我想写一些像......
@Pointcut("get(* abc.ThreadPoolService.*)")
public void drFields() {}
@AfterReturning(pointcut="drFields()", returning= **????** )
public void afterAccessingdrFields(what should come here???) {
LOGGER.info("Accessed the field drMaxTh " + <and here???>);
}
但是,如果是通配符字段访问说明符,则无法理解如何捕获正在访问的字段的名称和值。
感谢任何帮助我解决这个问题的人。
答案 0 :(得分:9)
实际上非常简单, sheltem 是正确的,你可以在返回的类型声明中使用Object
。这是一个小小的演示,表明它甚至适用于静态和非静态成员,只要它们未被声明final
:
驱动程序应用程序:
package de.scrum_master.app;
public class Application {
public static final double PI = Math.PI;
static String producer = "Scrum-Master.de";
private int id = 11;
private String author = "Alexander Kriegisch";
private final String COUNTRY = "Germany";
public static void main(String[] args) {
Object dummy;
Application application = new Application();
// Access static fields
dummy = PI;
dummy = producer;
// Access non-static fields
dummy = application.author;
dummy = application.id;
dummy = application.COUNTRY;
}
}
<强>方面:强>
package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class FieldAccessLogger {
@Pointcut("get(* de.scrum_master.app.Application.*)")
public void fieldAccess() {}
@AfterReturning(pointcut = "fieldAccess()", returning = "field")
public void afterFieldAccess(Object field, JoinPoint thisJoinPoint) {
System.out.println(thisJoinPoint.toLongString());
System.out.println(" " + thisJoinPoint.getSignature().getName());
System.out.println(" " + field);
}
}
控制台输出:
get(static java.lang.String de.scrum_master.app.Application.producer)
producer
Scrum-Master.de
get(private java.lang.String de.scrum_master.app.Application.author)
author
Alexander Kriegisch
get(private int de.scrum_master.app.Application.id)
id
11
如您所见,PI
和COUNTRY
未被拦截,因为它们是(最终)常量。