Bikas Katwal
Bikas Katwal

Reputation: 2035

getAnnotation returns null for methods in different maven module

I have create below annotation in maven module "A"

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface CacheDelete {...}

In the same module "A", I have TestPojo class, where I am using this annotation

@CacheDelete()
public void removeTestPojo(int id) {

}

I am calling this removeTestPojo() method from test case in module "A". Everything works fine here. I get the correct annotation using below code in my advice.

Advice method code CacheAspect class in module "A":

CacheDelete cacheDeleteAnnotation = getAnnotation((MethodSignature) joinPoint.getSignature(),
      CacheDelete.class);

Get annotation method:

private <T extends Annotation> T getAnnotation(MethodSignature methodSignature,
  Class<T> annotationClass) {
     return methodSignature.getMethod().getAnnotation(annotationClass);
}

Problem: Now I have a different module "B" where I am using dependency of "A" and one of the method in "B" module is annotated with @CacheDelete.

When I run the test case in module "B" for annotated method and debug the CacheAspect class, debug point comes to my advice, but my get annotation returns null here. Any one knows what could be the reason?

Upvotes: 2

Views: 1954

Answers (1)

Bikas Katwal
Bikas Katwal

Reputation: 2035

Got the problem it has nothing to do with different module. I annotated method that was implementation of an interface and was calling the implemented method through interface reference variable.

So when you use:

(MethodSignature) proceedingJoinPoint.getSignature().getMethod() 

it returns the method from interface;

Instead I replaced above code with:

MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = signature.getMethod();
String methodName = method.getName();
if (method.getDeclaringClass().isInterface()) {
  method = proceedingJoinPoint.getTarget().getClass().getDeclaredMethod(methodName,
      method.getParameterTypes());
}

So, this will check if method is interface, if so, I will invoke:

proceedingJoinPoint.getTarget().getClass().getDeclaredMethod()

which gives me method of subclass.

The strange thing is, when we call subclass method through interface, call propagates to the advice(AOP) when annotation used in subclass method but annotation doesn't propagate in subclass method.

Upvotes: 4

Related Questions