6

It's tough to make a concise title for this.

Anyway, imagine I have a parent class:

    public class Shape {
        public Dimensions getDimensions() {
            // Does some generic stuff.
        }
    }

I have a derived class from it that overrides the getDimensions method:

    public class Circle extends Shape {
        public Dimensions getDimensions() {
            // Does some stuff.
            super.getDimensions();
        }
    }

When I create an aspect with a pointcut on Shape.getDimensions, the pointcut is hit twice when Circle.getDimensions is called: once for Circle.getDimensions, then once when it calls super.getDimensions.

The pointcut looks something like this: @Pointcut("execution(* Shape.getDimensions(..))")

I've added a hack inside the advice to check the declaring type's name (using JoinPoint.getSignature().getDeclaringType().getName()), but I find it rather gross and it feels kind of like a hack. I figure there MUST be a better way to do this.

Is there?

Apologies if the formatting isn't very good. First time asking a question on here (I can usually find the answer already).

Depressio
  • 1,329
  • 2
  • 20
  • 39

1 Answers1

5

Probably you meant that your pointcut uses Shape+.getDimensions() (with the plus sign), otherwise it would not have matched Circle at all.

Anyway, you can solve the problem like this (I hope native AspectJ syntax is okay for you, I find it so much clearer and more expressive):

public aspect ShapeAspect {
    pointcut getDimensions() : execution(* Shape+.getDimensions());
    pointcut getDimensionsNoSuper() : getDimensions() && !cflowbelow(getDimensions());

    after() : getDimensionsNoSuper() {
        System.out.println(thisJoinPointStaticPart);
    }
}
kriegaex
  • 63,017
  • 15
  • 111
  • 202
  • Works beautifully, thanks. I'm more used to the annotation style, but the key was the cflowbelow call. In the process of trying to figure out if I could condense that into a single advice (couldn't figure it out), I found this lovely appendix: http://www.eclipse.org/aspectj/doc/next/progguide/semantics-pointcuts.html – Depressio Aug 31 '12 at 15:18
  • I apparently need 15 points to do so. I only have 11. Believe me, I tried! :( – Depressio Aug 31 '12 at 17:16
  • actually `execution` would also match superclass method,no matter if there is a `+` – Xiao Apr 12 '13 at 04:02
  • @Sean: This is why the pointcut has another condition which filters out the execution of the superclass method. Have you even tried? – kriegaex Apr 12 '13 at 07:13