The pertypewithin Aspect Instantiation Model
AspectJ 5 defines a new per-clause type for aspect instantiation:
pertypewithin. Unlike the other per-clauses,
pertypewithin takes a type pattern:
When an aspect is declared using the pertypewithin
instantiation model, one new aspect instance will be created for each
type matched by the associated type pattern.
Pertypewithin aspects have aspectOf and
hasAspect methods with the following signatures:
Where P is the type of the pertypewithin
aspect.
In common with the other per-clause instantiation models, the execution
of any advice declared within a pertypewithin aspect
is conditional upon an implicit pointcut condition. In this case, that
any join point be within the type that the executing
aspect is an aspectOf. For example, given the aspect
definition
> instances = new HashSet>();
after(Object o) returning : execution(new(..)) {
instances.add(new WeakReference
Then one aspect instance will be created for each type within
org.xyz..*. For each aspect instance, the
after returning advice will match only the execution of constructors
in the type that the aspect is an instance of. The net result is that
the aspect tracks all known instances of each type within
org.xyz..*. To get access to the instances, a
programmer can simply write
InstanceTracking.instanceOf(org.xyz.SomeType).getInstances().
A pertypewithin aspect may optionally be declared
with a single generic type parameter. In this case, for each type
T matched by the type pattern, the aspect instance
created will be of type PerTypeWithinAspect<T>.
So the previous example could also be written as:
pertypewithin(org.xyz..*) {
private Set> instances = new HashSet>();
after(T t) returning : execution(new(..)) {
instances.add(new WeakReference(t);
}
public Set getInstances() {
Set result = new HashSet();
for(WeakReference ref : instances) {
if (ref.get() != null) {
result.add(ref.get());
}
}
return result;
}
}
]]>
The pertypewithin aspect instantiation model should
be used when the implementation of a crosscutting concern requires that
some state be maintained for each type in a set of types. To maintain
state for a single type, it is easier to use a static inter-type declared
field. Examples of usage include instance tracking, profiling, and the
implementation of a common tracing idiom that uses one Logger per
traced class.