aspectJ中的字段读字段写访问

Field read field write access in aspectJ

我是 aspectJ 的新手。我想了解字段读取访问和字段写入访问切入点。假设我的 class "Field" 中有一个私有静态字符串变量 "name"。

private static String name;

我需要在读取名称时赋值并在设置时抛出异常。

下面是aspectJ代码。

package main.java.testaop.field;
public aspect FieldAspect {
pointcut getName() : get(private static String Field.name);
pointcut setName() : set(private static String Field.name);
before() : getName() {
"john";}
before() : setName() {
throw new Exception(); }

编译时出现错误。我知道这是错误的。谁能帮助我了解这是如何工作的。

您想访问私有字段(这是可能的,但在概念上有点异味)。为了做到这一点,将您的方面声明为特权:

public privileged aspect FieldAspect { ... }