Frankie
Frankie

Reputation: 25165

Isolate methods with same name based on type using AspectJ?

Say I have a pointcut on the run() method.

pointcut run(): execution(public void *.run());
before(): run() {
    // do something with run
}

But I only want to catch some instances of run. For example:

new Thread(new Runnable() {
    @Override
    public void run() {
        // this run should be intercepted
    }
});

new Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        // this run should be ignored
    }
}, 0, 1000);

How can I change my pointcut to forget about the run() that's not from a Thread?

Upvotes: 1

Views: 66

Answers (2)

Frankie
Frankie

Reputation: 25165

Edit: while the code bellow works do check Nándor Előd Fekete accepted answer as it's much more efficient.

From AspectJ Cookbook was pretty easy to infer the solution:

pointcut run(): execution(public void *.run()) && !target(java.util.TimerTask);
before(): run() {
    // do something with run, will not catch instances of TimerTask
}

Upvotes: 0

Nándor Előd Fekete
Nándor Előd Fekete

Reputation: 7098

If you would like to advise all implementations of the Runnable.run() method except where the class providing the implementation of that run method is a subclass of TimerTask, it can be done efficiently with the following pointcut expression:

execution(public void Runnable+.run()) && !execution(public void java.util.TimerTask+.run());

Upvotes: 1

Related Questions