Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [aspectj-users] Advice on Constructors With Subclasses

What about this :

public aspect CheckingWithSimplestAspectJEver {

    pointcut constructor(A inst) : execution(A+.new(..)) && this(inst);

    after(A inst) : constructor(inst) {
        if (inst.getClass().equals(
        thisJoinPointStaticPart.getSourceLocation().getWithinType()))
           System.out.println("Done with " +
              inst.getClass().getSimpleName());
    }
}

It works also with classes that instantiate another subclass of A inside
their constructors, for example delegate classes :

public class Delegate extends B {

    private C another;

    public Delegate() {
        this.another = new C();
        System.out.println("Doing stuff in delegate");
    }

}

new Delegate()

I'm in A
I'm in B
I'm in A
I'm in B
I'm in C
Done with C
Doing stuff in delegate
Done with Delegate

I think we can happily close the enhancement request, and focus more on
what the AspectJ API offers :)

Simone



BiggusJimmus wrote:
> I am attempting to write some advice that will run only after the
> construction has completely finished, i.e. after the an object has been
> completely initialized.
>
> An object can be created in any of the types in an inheritance tree, and
> thus, I would like to advise all of the constructors, but only run the
> advice once, after the object has been constructed.
>
> This is probably easier to describe via an example:
>
> public class A {
>     public A() {
>         System.out.println("init A");
>     }
> }
>
> public class B extends A {
>     public B() {
>         super();
>         System.out.println("init B");
>     }
> }
>
> public class C extends B {
>     public C() {
>         super();
>         System.out.println("init C");
>     }
> }
>
> after(A item) : execution(A+.new()) && target(item) {
>     System.out.println(thisJoinPoint.getSourceLocation());
> }
>
> public static void main(String[] args) {
>     C c = new C();
>     B b = new B();
> }
>
> The above code has the following output:
> init A
> A.java:3
> init B
> B.java:3
> init C
> C.java:3
>
> init A
> A.java:3
> init B
> B.java:3
>
> What I am attempting to create is advice that will produce the following:
> init A
> init B
> init C
> C.java:3
>
> init A
> init B
> B.java:3
>
> i.e. Only run the advice after the object is completely created
>
> I have tried a few approaches, including !within(A+.new()) and
> !cflow(execution(A+.new()), but due to the way the compiler inlines the
> super() calls, these approaches produce the same results as above.
>
> Does anybody have any experience with this problem, and/or suggestions on
> how to solve it?
>   


-- 
Simone Gianni
http://www.simonegianni.it/
CEO Semeru s.r.l.
Apache Committer




Back to the top