简体   繁体   中英

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

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 *).*(..))")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM