你不能用代理来做到这一点,但真正的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
考虑您的解决方案后,我意识到这可能比其根本@nonblocking的直列转让更好,因为它应该对于知道“重”的对象是固有的。所以我暂时满意......谢谢! – 2010-08-19 20:22:30