プロキシを使用してこれを行うことはできませんが、ローカル変数の代わりに型に注釈を付けると、実際のアスペクトJバイトコードの織り込みが可能になります。(ローカル変数アクセスはポイントカットとしてサポートされていないと思います)。とにかく、ここにいくつかのコードがあります。
注釈:
@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