Ikthiander
Ikthiander

Reputation: 3917

how to get the Annotated object using aspectJ

I have an annotation like this:

@Inherited
@Documented
@Target(value={ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Restful {

}

I annotated this class like this:

@Restful
public class TestAspect {
   public String yes;
}

I have a pointcut like this:

@Pointcut("@annotation(com.rest.config.Restful)")
   public void pointCutMethod() {
}

I tried:

@Before("pointCutMethod()")
public void beforeClass(JoinPoint joinPoint) {
    System.out.println("@Restful DONE");
    System.out.println(joinPoint.getThis());
}

But getThis() returns null.

Basically I am trying to get that Object instance of TestAspect. How do I do it? Any clue? any help would be really appreciated.

Thanks in advance

Upvotes: 2

Views: 157

Answers (1)

Andy Clement
Andy Clement

Reputation: 2560

With your annotation placed on the type only and the pointcut @annotation(com.rest.config.Restful) you are only going to match the static initialization join point for your type. As we can see if you use -showWeaveInfo when you compile (I slapped your code samples into a file called Demo.java):

Join point 'staticinitialization(void TestAspect.<clinit>())' in 
  Type 'TestAspect' (Demo.java:9) advised by before advice from 'X' (Demo.java:19)

When the static initializer runs there is no this, hence you get null when you retrieve it from thisJoinPoint. You haven't said what you actually want to advise but let me assume it is creation of a new instance of TestAspect. Your pointcut needs to match on execution of the constructor for this annotated type:

// Execution of a constructor on a type annotated by @Restful
@Pointcut("execution((@Restful *).new(..))")
public void pointcutMethod() { }

If you wanted to match methods in that type, it would be something like:

@Pointcut("execution(* (@Restful *).*(..))")

Upvotes: 1

Related Questions