Adrian Colyer, lead of the AspectJ team, was obviously a busy man on his flight back from Las Vegas to London.
He posted a message to the aspectj mailling list, which talks about a JoinPointMatcher. This class is built to handle dynamically working with join points a la:
JoinPointMatcher jpm = new JoinPointMatcher("within(patterntesting..*)");
He says more:
At any join point, you can ask JoinPointMatcher whether or not it matches:
if( jpm.matches(thisJoinPoint)) ...
Here's an aspect that allows runtime configuration using this mechanism:
aspect DynamicPointcutConstructionExample {
private static JoinPointMatcher jpm;
public void setPointcutExpression(String pointcutExpr) {
jpm = new JoinPointMatcher(pointcutExpr);
}
// this pointcut is used to narrow down as far as possible at compile time the set of places
// at which a dynamic pointcut could match (for efficiency)
pointcut scope() : within(org.xyz.foo);
before() : scope() && if(jpm.matches(thisJoinPoint)) {
System.out.println("I matched!!");
}
}
The consequence you pay for using dynamic pointcuts (I'm using the word dynamic in analogy to the use of "dynamic" in DII, it may not be the best
term) is that the pointcut matching is (very much) less efficient since the jpm.match code is driven for every join point in the scope (whereas the same pointcut specified at compile time would cause the advice to execute exactly where it needs to with no additional overhead or redundancy). If a dynamic pointcut proved to be too slow, you could always switch back to a traditional statically specified pc.
If you're using Spring with the above example, you can configure the aspect with e.g.
"http://www.springframework.org/dtd/spring-beans.dtd">
I hope we end up with something very close to this in Spring -->
class="DynamicPointcutConstructionExample"
factoryMethod="aspectOf">
execution(* *(..)) && this(Foo)
Spring will set the value of the pointcutExpression attribute when the aspect is constructed. Many thanks are due to Rod Johnson for the inspiration to look into this.
This is *very* cool stuff. I know that Vincent Massol has a need for this type of dynamic pointcut, and many others will be found. Of course, you want to NOT do things in this manner when possible for performance reasons etc.... but having the power to drop down to this when needed is fantastic.
Now all we need is to have the ability to write reusable aspect libraries and I will be a very happy man.