2

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

@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 并不真正支持它们,但它会很神奇。我真的不想传递 Future 并打破封装。

4

1 回答 1

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

}

当您将 HeavyLifter 作为 Eclipse 中的 AspectJ/Java 应用程序运行时,以下是其输出:

Finished with main
Wait... this is too heavy
OK, now I am up to the task
Boy, I am heavy
于 2010-08-18T14:33:43.240 回答