2

ローカル変数の注釈を使用して、AOP を改善したいと考えています。1 つのアイデアは、注釈を使用してプロキシを使用して 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

プロキシを使用してこれを行うことはできませんが、ローカル変数の代わりに型に注釈を付けると、実際のアスペクト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
于 2010-08-18T14:33:43.240 に答える