Search code examples
javaaopaspectjpointcut

AspectJ - How to catch constructor call also for subclasses?


I have an abstract class Foo.

I want to have a compile error if I create a new instance of a concrete class that extends Foo outside an Aspect named Bar.

I tried this:

public pointcut errorcall(): call(Foo.new(..)) && !within(Bar);
declare error: errorcall():"Error: You must use Bar creation methods!";

But it doesn't catch the subclasses of Foo.

If I declare the pointcut as:

public pointcut errorcall(): call(ConcreteFoo.new(..)) && !within(Bar);

It catches the ConcreteFoo creation outside Bar, but I would like to intercept every subclass of Foo.

How can I do it?


Solution

  • The MyClass+ notation also grabs subclasses. This information can be found in any AspectJ tutorial, e.g. here:

    public pointcut errorcall():
      call(Foo+.new(..)) && !within(Bar);