Java 带局部变量注释的AOP

Java 带局部变量注释的AOP,java,annotations,aop,aspectj,Java,Annotations,Aop,Aspectj,我想使用局部变量注释来更好地实现AOP。一个想法是通过使用注释的代理来实现未来的概念 @NonBlocking ExpensiveObject exp = new ExpensiveObject(); //returns immediately, but has threaded out instantiation of the ExpensiveObject. exp.doStuff(); //okay, now it blocks until it's finished instant

我想使用局部变量注释来更好地实现AOP。一个想法是通过使用注释的代理来实现未来的概念

@NonBlocking ExpensiveObject exp = new ExpensiveObject(); 
//returns immediately, but has threaded out instantiation of the ExpensiveObject.

exp.doStuff(); 
//okay, now it blocks until it's finished instantiating and then executes #doStuff

我能不能在这一点上对AspectJ有点反感,然后用局部变量注释来完成我想要的工作?我知道其他线程表明Java并不真正支持它们,但这将是不可思议的。我真的不想在将来转弯抹角,破坏封装。

使用代理无法做到这一点,但如果您注释类型而不是局部变量,真正的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");
    }
}
用此批注标记的类:

@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();
    }

}
以下是HeavyLifeter在eclipse中作为AspectJ/Java应用程序运行时的输出:

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

在考虑了您的解决方案之后,我意识到它可能比使用@nonblocking的内联赋值要好,因为它应该是对象固有的,知道它是“重的”。所以我现在很满意。。。谢谢