I would like to create a class that pointcuts to methods within the list interface. This seems to work until I add the target(list) to my advice. I would like to view the elements of a list before and after adding to (for example) see what has changed but I cannot seem to pass my list in as I would an object. Here is what I have so far, this does not run with the target(list) but does run without it :
pointcut addPointCut() : call(boolean List.add(..));
before(List<Integer> list) : addPointCut() && target(list) {
System.out.println("testing");
for(Object i : list) {
System.out.println(i);
}
}
Nándor's answer is correct insofar as he describes the compiler error you see. I want to go a little further and also explain why you get this error:
First of all, the problem is not directly related to AspectJ but rather to how Java implements generics. Please make yourself familiar with a phenomenon called type erasure before you continue to read.
Well, because type erasure is a JVM reality and because
target()andthis()are resolved during runtime rather than compile time - you can indirectly conclude this from the fact that bothgetTarget()andgetThis()are methods ofJoinPointrather thanJoinPoint.StaticPart- what you want to do cannot work and consequently leads to an AspectJ compiler error. The only thing you can do is useinstanceofin order to dynamically determine what gets added to the target list. The most elegant way to do this is anif()pointcut expression.Here is some sample code:
Driver application:
So as to make things a little more interesting we use two types of lists and also two types of
add(..)calls. The goal should be to only intercept integers to be added to the corresponding list, no matter which signature theadd(..)method has.Aspect:
Console log:
Any further questions?