2010-07-23 55 views
2

我想使用局部变量注释来做更好的AOP。其中一个想法是通过使用注释的代理实现未来的<T>概念。带局部变量注释的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并不真的支持它们,但它会是神奇的。我真的不想传递未来并破坏封装。

回答

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 
+0

考虑您的解决方案后,我意识到这可能比其根本@nonblocking的直列转让更好,因为它应该对于知道“重”的对象是固有的。所以我暂时满意......谢谢! – 2010-08-19 20:22:30