How to define an aspectj pointcut that picks out all constructors of a class that has a specific annotation?

前端 未结 3 1361
一向
一向 2021-01-20 18:20

Here is the annotation:

@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation {
    String          


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-20 18:53

    THE FOLLOWING WORKS, BUT IS NOT RECOMMENDED BY kriegaex. PROVIDED HERE AS POSSIBLE MATERIAL THAT COULD BE REPURPOSED IF THE NEED ARISES.

    This was my first working solution to the problem which uses in part the initialization() pointcut primitive.

    public aspect AnnotationTests {
      private pointcut genericConstructor(): initialization(*.new(..));
      private pointcut withinMyAnnotation(): @within(MyAnnotation);
      private pointcut constructorInAnnotatedClass(): genericConstructor()
          && withinMyAnnotation();
    
      before(): constructorInAnnotatedClass() && !cflowbelow(constructorInAnnotatedClass()) {
        final Object objectInstance = thisJoinPoint.getTarget();
        System.out.println("Object class name at join point: "
            + objectInstance.getClass().getName());
      }
    }
    
    @MyAnnotation(name="foo")
    public class ClassA {
      public ClassA() {
        // Do something
      }
    
      public static void main(String[] args) {
        ClassA classA = new ClassA();
        ClassB classB = new ClassB("");
        if (classA.getClass().getName().equals(classB.getClass().getName())) {
            throw new RuntimeException("Big problems!");
        }
      }
    }
    
    @MyAnnotation(name="bar")
    public class ClassB {
      private final String aString;
    
      public ClassB(String aString) {
        this.aString = aString;
      }
    }
    

提交回复
热议问题