1

I read many question in this forum but nothing works.

public @interface MyAnnotation {
    String value() default "";
    Class[] exceptionList;
}

@MyAnnotation(value="hello", exceptionList={TimeOutException.class})
public void method() {}


@Aspect
public class MyAspect {
    @Around("@annotation(MyAnnotation)")
    public Object handle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) {
        System.out.println(myAnnotation.exceptionList); // should print out TimeOutException
    }
}

How can I get the value and the exceptionList of the @MyAnnotation while executing the advice? I'm using Spring 4.0.6, AspectJ 1.7.4

Esca Tran
  • 129
  • 1
  • 3
  • 14

2 Answers2

1

The solution for this is making sure the advice method's parameter name match the parameter name in AspectJ expression. In my case, the advice method should look like this:

@Aspect
public class MyAspect {
    @Around("@annotation(myAnnotation)")
    public Object handle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) {
        System.out.println(myAnnotation.exceptionList); // should print out TimeOutException
    }
}
Esca Tran
  • 129
  • 1
  • 3
  • 14
0

You are already almost there. Probably.

You are using the correct way to retrieve the annotation, so you have the values available.

Your problem - if I interpret the very minimalistic problem description(!) you only provide via the comment in your code snippet(!) correctly - is the (wrong) assumption that sticking an array of the type Class into System.out.println() will print out the names of the Classes it contains. It does not. Instead it prints information about the reference:

[Ljava.lang.Class;@15db9742

If you want the names of the Classes, you will have to iterate over the elements of that array and use .getName(), .getSimpleName() or one of the other name providing methods of Class.

Further information on how to print elements of an array is here:

What's the simplest way to print a Java array?

Granted, this whole answer could be entirely besides the point if the problem is that you are getting null values from the annotation fields. But since you have not provided an adequate problem description ("nothing works" is not a problem description!), we can only guess at what your problem is.

Community
  • 1
  • 1
sheltem
  • 3,754
  • 1
  • 34
  • 39
  • Hi Sheltem. "Nothing works" means the IDE complains " formal unbound in pointcut". Fortunately, I found the root cause: `@Around("@annotation(MyAnnotation)")` should be `@Around("@annotation(myAnnotation)")` instead. Because the parameter name of the advice method is myAnnotation. – Esca Tran Jun 02 '15 at 13:49
  • Hm. Good on you to find it then, that's a detail I missed. I'll still leave this answer around to remind you to provide a full problem description including all IDE error output next time. ;) – sheltem Jun 02 '15 at 13:51