Skip to content

Instantly share code, notes, and snippets.

@ohdoking
Created January 28, 2020 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohdoking/596998c519c55d54f50d7524ba032f9d to your computer and use it in GitHub Desktop.
Save ohdoking/596998c519c55d54f50d7524ba032f9d to your computer and use it in GitHub Desktop.
replace value with AOP
//https://stackoverflow.com/questions/45673978/aspectj-change-value-of-method-parameter
@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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment