时间:2010-07-23 23:46:40

标签: java annotations aop aspectj

1 个答案:

答案 0 :(得分:2)

您不能使用代理执行此操作,但是如果您注释类型而不是局部变量,那么真正的aspectj字节码编织将使您到达那里。 (我不认为支持局部变量访问作为切入点)。无论如何,这里有一些代码。

注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Later {}

标有此注释的类:

package com.dummy.aspectj;
@Later
public class HeavyObject{

    public HeavyObject(){
        System.out.println("Boy, I am heavy");
    }
}

主要课程:

package com.dummy.aspectj;
public class HeavyLifter{

    public static void main(final String[] args){
        final HeavyObject fatman = new HeavyObject();
        System.out.println("Finished with main");
    }

}

和方面:

package com.dummy.aspectj;
public aspect LaterAspect{

    pointcut laterInstantiation() :
        execution(@Later *.new(..))    ;

    void around() : laterInstantiation() {
        new Thread(new Runnable(){
            @Override
            public void run(){
                System.out.println("Wait... this is too heavy");

                try{
                    Thread.sleep(2000);
                } catch(final InterruptedException e){
                    throw new IllegalStateException(e);
                }
                System.out.println("OK, now I am up to the task");
                proceed();
            }
        }).start();
    }

}

当你从eclipse运行它作为AspectJ / Java应用程序时,这是HeavyLifter的输出:

Finished with main
Wait... this is too heavy
OK, now I am up to the task
Boy, I am heavy