在本例中,我想拦截对用 MyAnnotation 注释的字段的所有分配。如果在通过反射赋值时它可以工作,那就更好了。 这是我尝试过的,但它没有运行,我认为可能还有其他问题:
public privileged aspect MyAnnotationAspect {
pointcut hasAnnotation(MyAnnotation annotation) : @annotation(annotation);
pointcut methodExecution() : execution(* *(..));
Object around(MyAnnotation annotation) : set(String word) && methodExecution() && hasAnnotation(annotation) {
Object result = null;
try {
result = proceed(annotation, "new"); //Just to try I want to assign "new" instead of the variable word
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
return result;
}
}
它表示方法继续的参数太多。谁能帮我?谢谢!
编辑
现在它抛出“警告:(10, 0) ajc:方面中定义的建议。AnnotationAspect 尚未应用 [Xlint:adviceDidNotMatch]”
这是我的方面:
public aspect AnnotationAspect {
pointcut hasAnnotation(Annotation annotation) : @annotation(annotation);
Object around(Annotation annotation, String word) : hasAnnotation(annotation) && set(String *) && args(word) {
Object result = null;
System.out.println(thisJoinPoint);
try {
result = proceed(annotation, "intercepted");
} catch (RuntimeException ex) {
throw ex;
}
return result;
}
}
这是注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Annotation {
}
我有一个假人来测试它:
class DummyEntity{
@Annotation
var name: String =_
def setName(n: String): Unit ={
name = n
}
}
这是我正在测试的测试:
public class AnnotationAspectTest {
private DummyEntity dummyEntity;
@Before
public void setUp(){
dummyEntity = new DummyEntity();
}
@Test
public void testing(){
dummyEntity.setName("newName");
Assert.assertEquals("intercepted", dummyEntity.name());
}
}
最佳答案
methodExecution()
在这里会适得其反,因为您不想捕获方法执行,而是捕获字段写入访问。因为 set(..) &&execution(..)
是互斥的,所以这没有逻辑意义。
此外,您需要通过 args() 将分配的值绑定(bind)到参数,以便能够对其进行修改。
package de.scrum_master.aspect;
import de.scrum_master.app.MyAnnotation;
public aspect MyAnnotationAspect {
Object around(MyAnnotation annotation, String word) :
@annotation(annotation) && set(String *) && args(word)
{
System.out.println(thisJoinPoint);
Object result = null;
try {
result = proceed(annotation, "altered value");
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
return result;
}
}
关于java - 调用使用 AspectJ 注释的字段的 setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43374990/