Created
January 28, 2020 15:32
-
-
Save ohdoking/596998c519c55d54f50d7524ba032f9d to your computer and use it in GitHub Desktop.
replace value with AOP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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