AspectJ-方法参数的更改值

mor*_*h84 3 java annotations aspectj

我想要这样的东西:

public void doSomething(@ReplaceFooBar String myString) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

ReplaceFooBar是我的自定义注释,在方法开始执行之前,它应该采用的值,myString并在其replaceAll上加上“ bar”,然后对它进行“ foo”的操作,以便它以新的字符串值执行。因此,如果使用参数“ I'm at the foo”调用该方法。它实际上应与“我在酒吧”一起执行。

我不知道该怎么做。我已经摆弄了一段时间。假设我最后结束了这一点:

@Documented
@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReplaceFooBar {
}
Run Code Online (Sandbox Code Playgroud)

和...

@Aspect
public aspect ReplaceFooBarAspect {
    @Before("@annotation(ReplaceFooBar)")
    public String replaceFooBar(String value) {
        if (value == null) {
            return null;
        }
        return value.replaceAll("foo", "bar");
    }
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

我的代码未编译,出现了此类错误。

Error:(6, 0) ajc: Duplicate annotation @Aspect
Error:(7, 0) ajc: aspects cannot have @Aspect annotation
Error:(10, 0) ajc: This advice must return void
Error:(10, 0) ajc: formal unbound in pointcut
Run Code Online (Sandbox Code Playgroud)

我不知道这些方面如何工作,如何以我想要的方式工作。

Vla*_*nin 5

要使用不同的参数执行方法,应使用@Around建议并在代码中手动替换参数。

例如:

@Around("execution(* *(.., @aspectjtest.ReplaceFooBar (*), ..))")
public Object replaceFooBar(ProceedingJoinPoint pjp) throws Throwable {
    //get original args
    Object[] args = pjp.getArgs();

    //get all annotations for arguments
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    String methodName = signature.getMethod().getName();
    Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
    Annotation[][] annotations;
    try {
        annotations = pjp.getTarget().getClass().
                getMethod(methodName, parameterTypes).getParameterAnnotations();
    } catch (Exception e) {
        throw new SoftException(e);
    }

    //Find annotated argument
    for (int i = 0; i < args.length; i++) {
        for (Annotation annotation : annotations[i]) {
            if (annotation.annotationType() == ReplaceFooBar.class) {
                Object raw = args[i];
                if (raw instanceof String) {
                    // and replace it with a new value
                    args[i] = ((String) raw).replaceAll("foo", "bar");
                }
            }
        }
    }
    //execute original method with new args
    return pjp.proceed(args);
}
Run Code Online (Sandbox Code Playgroud)