Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring AOP get method parameter value based on parameter name

Is it possible to get the method parameter value based on parameter name in Spring AOP.

MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();

Method method = signature.getMethod();

method.getParameters().getName() 
// possible to get the paramater names 

This approach will get parameter names, not value.

proceedingJoinPoint.getArgs()

will return values not names

Then is it possible to get the value based on a parameter name?

like image 811
Cork Kochi Avatar asked Aug 17 '17 13:08

Cork Kochi


People also ask

How do I get method parameters in AOP?

First, you can use the JoinPoint#getArgs() method which returns an Object[] containing all the arguments of the advised method. You might have to do some casting depending on what you want to do with them.

What is Joinpoint proceed ()?

In summary, joinPoint. proceed(); means that you are calling the set method, or invoking it. Follow this answer to receive notifications.

Does Spring AOP use AspectJ?

In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).


1 Answers

As I searched everywhere does not exist a function that gives parameter value by name and I wrote a simple method that makes this work.

public Object getParameterByName(ProceedingJoinPoint proceedingJoinPoint, String parameterName) {
    MethodSignature methodSig = (MethodSignature) proceedingJoinPoint.getSignature();
    Object[] args = proceedingJoinPoint.getArgs();
    String[] parametersName = methodSig.getParameterNames();

    int idx = Arrays.asList(parametersName).indexOf(parameterName);

    if(args.length > idx) { // parameter exist
        return args[idx];
    } // otherwise your parameter does not exist by given name
    return null;

}
like image 66
FarukT Avatar answered Sep 28 '22 14:09

FarukT