Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the java.lang.reflect.Method from a ProceedingJoinPoint?

The question is short and simple: Is there a way to get the Method object from an apsectj ProceedingJoinPoint?

Currently I am doing

Class[] parameterTypes = new Class[joinPoint.getArgs().length];
Object[] args = joinPoint.getArgs();
for(int i=0; i<args.length; i++) {
    if(args[i] != null) {
        parameterTypes[i] = args[i].getClass();
    }
    else {
        parameterTypes[i] = null;
    }
}

String methodName = joinPoint.getSignature().getName();
Method method = joinPoint.getSignature()
    .getDeclaringType().getMethod(methodName, parameterTypes);

but I don't think this is the way to go ...

like image 348
Erik Avatar asked Apr 19 '11 09:04

Erik


People also ask

How do I get the method name from ProceedingJoinPoint?

ProceedingJoinPoint Get Parameter Names and Values If for some reason, you need to get the joinpoint parameter names, you can use ((MethodSignature)ProceedingJoinPoint. getSignature()). getParameterNames() . This returns a String array with the names of the parameters passed to your joinpoint.

What is ProceedingJoinPoint?

ProceedingJoinPoint is an extension of the JoinPoint that exposes the additional proceed() method.


2 Answers

Your method is not wrong, but there's a better one. You have to cast to MethodSignature

MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
like image 181
Bozho Avatar answered Oct 16 '22 09:10

Bozho


You should be careful because Method method = signature.getMethod() will return the method of the interface, you should add this to be sure to get the method of the implementation class:

    if (method.getDeclaringClass().isInterface()) {
        try {
            method= jointPoint.getTarget().getClass().getDeclaredMethod(jointPoint.getSignature().getName(),
                    method.getParameterTypes());
        } catch (final SecurityException exception) {
            //...
        } catch (final NoSuchMethodException exception) {
            //...                
        }
    }

(The code in catch is voluntary empty, you better add code to manage the exception)

With this you'll have the implementation if you want to access method or parameter annotations if this one are not in the interface

like image 47
Nordine Avatar answered Oct 16 '22 07:10

Nordine