3

@ReferencedResourceカスタム注釈または別の注釈で注釈が付けられた wicket コンポーネントの大規模なライブラリがあり、複数の注釈を許可するパラメーター@ReferencedResourcesがあります。ReferencedResouce[] value()

サンプル コード スニペットを次に示します。

@ReferencedResources({
    @ReferencedResource(value = Libraries.MOO_TOOLS, type = ResourceType.JAVASCRIPT),
    @ReferencedResource(value = "behaviors/promoteSelectOptions", type = ResourceType.JAVASCRIPT) })
public class PromoteSelectOptionsBehavior extends AbstractBehavior{
 ...
}

ここまでは、aptを使用して参照先のリソースが実際に存在することを確認しました。例えば

@ReferencedResource(value = "behaviors/promoteSelectOptions",
                     type = ResourceType.JAVASCRIPT)

js/behaviors/promoteSelectOptions.jsファイルがクラスパスで見つからない限り、コンパイルは失敗します。この部分はうまく機能します。

現在、私は DRY のファンでもあり、同じアノテーションを使用して、オブジェクトが作成されたときに実際にリソースをオブジェクトに注入したいと考えています。AspectJ を使用して、この一部を実装しました。

注釈付きオブジェクトは、常にComponentまたはAbstractBehaviorのいずれかのインスタンスです。

コンポーネントの場合は簡単で、コンストラクターの後に一致させるだけです。これを行うアドバイスは次のとおりです。

pointcut singleAnnotation() : @within(ReferencedResource);

pointcut multiAnnotation() : @within(ReferencedResources);

after() : execution(Component+.new(..)) && (singleAnnotation() || multiAnnotation()){
    final Component component = (Component) thisJoinPoint.getTarget();
    final Collection<ReferencedResource> resourceAnnotations =
        // gather annotations from cache
        this.getResourceAnnotations(component.getClass());
    for(final ReferencedResource annotation : resourceAnnotations){
        // helper utility that handles the creation of statements like
        // component.add(JavascriptPackageResource.getHeaderContribution(path))
        this.resourceInjector.inject(component, annotation);
    }
}

ただし、動作の場合は、動作自体ではなく、応答にリソースを添付する必要があります。私が使用するポイントカットは次のとおりです。

pointcut renderHead(IHeaderResponse response) :
    execution(* org.apache.wicket.behavior.AbstractBehavior+.renderHead(*))
        && args(response);

そして、ここにアドバイスがあります:

before(final IHeaderResponse response) : 
    renderHead(response) && (multiAnnotation() || singleAnnotation()) {
    final Collection<ReferencedResource> resourceAnnotations =
        this.getResourceAnnotations(thisJoinPoint.getTarget().getClass());
    for(final ReferencedResource resource : resourceAnnotations){
        this.resourceInjector.inject(response, resource);
    }
}

これは、クラスがrenderHead(response)メソッドをオーバーライドする場合にもうまく機能しますが、多くの場合、スーパー クラスは基本機能を既に実装しているのに対し、子クラスはいくつかの構成を追加するだけであるため、必要ありません。したがって、1 つの解決策は、これらのクラスに次のようなメソッドを定義させることです。

@Override
public void renderHead(IHeaderResponse response){
    super.renderHead(response);
}

これはデッド コードであるため、私はこれを嫌いますが、現在これが唯一の有効なオプションであるため、他の解決策を探しています。

編集:

APT と sun javac 呼び出しを使用して、実用的なソリューションを作成しました。ただし、これは次の問題につながります。maven を使用して同じプロジェクトで APT と AspectJ を実行することです。

とにかく、時間ができ次第、この質問 (またはその一部) への回答を投稿します。

4

1 に答える 1

4

私自身の質問に答える:

スーパーコールを挿入するための関連コードは次のとおりです。

これらのフィールドはすべてinit(env)またはprocess(annotations, roundEnv)で初期化されます:

private static Filer filer;
private static JavacProcessingEnvironment environment;
private static Messager messager;
private static Types types;
private static JavacElements elementUtils;
private Trees trees;
private TreeMaker treeMaker;
private IdentityHashMap<JCCompilationUnit, Void> compilationUnits;
private Map<String, JCCompilationUnit> typeMap;

そして、アノテーションを持つ のサブタイプがメソッドAbstractBehaviorをオーバーライドしない場合に呼び出されるロジックは次のとおりです。renderHead(response)

private void addMissingSuperCall(final TypeElement element){
    final String className = element.getQualifiedName().toString();
    final JCClassDecl classDeclaration =
        // look up class declaration from a local map 
        this.findClassDeclarationForName(className);
    if(classDeclaration == null){
        this.error(element, "Can't find class declaration for " + className);
    } else{
        this.info(element, "Creating renderHead(response) method");
        final JCTree extending = classDeclaration.extending;
        if(extending != null){
            final String p = extending.toString();
            if(p.startsWith("com.myclient")){
                // leave it alone, we'll edit the super class instead, if
                // necessary
                return;
            } else{
                // @formatter:off (turns off eclipse formatter if configured)

                // define method parameter name
                final com.sun.tools.javac.util.Name paramName =
                    elementUtils.getName("response");
                // Create @Override annotation
                final JCAnnotation overrideAnnotation =
                    this.treeMaker.Annotation(
                        Processor.buildTypeExpressionForClass(
                            this.treeMaker,
                            elementUtils,
                            Override.class
                        ),
                        // with no annotation parameters
                        List.<JCExpression> nil()
                    );
                // public
                final JCModifiers mods =
                    this.treeMaker.Modifiers(Flags.PUBLIC,
                        List.of(overrideAnnotation));
                // parameters:(final IHeaderResponse response)
                final List<JCVariableDecl> params =
                    List.of(this.treeMaker.VarDef(this.treeMaker.Modifiers(Flags.FINAL),
                        paramName,
                        Processor.buildTypeExpressionForClass(this.treeMaker,
                            elementUtils,
                            IHeaderResponse.class),
                        null));

                //method return type: void
                final JCExpression returnType =
                    this.treeMaker.TypeIdent(TypeTags.VOID);


                // super.renderHead(response);
                final List<JCStatement> statements =
                    List.<JCStatement> of(
                        // Execute this:
                        this.treeMaker.Exec(
                            // Create a Method call:
                            this.treeMaker.Apply(
                                // (no generic type arguments)
                                List.<JCExpression> nil(),
                                // super.renderHead
                                this.treeMaker.Select(
                                    this.treeMaker.Ident(
                                        elementUtils.getName("super")
                                    ),
                                    elementUtils.getName("renderHead")
                                ),
                                // (response)
                                List.<JCExpression> of(this.treeMaker.Ident(paramName)))
                            )
                     );
                // build code block from statements
                final JCBlock body = this.treeMaker.Block(0, statements);
                // build method
                final JCMethodDecl methodDef =
                    this.treeMaker.MethodDef(
                        // public
                        mods,
                        // renderHead
                        elementUtils.getName("renderHead"),
                        // void
                        returnType,
                        // <no generic parameters>
                        List.<JCTypeParameter> nil(),
                        // (final IHeaderResponse response)
                        params,
                        // <no declared exceptions>
                        List.<JCExpression> nil(),
                        // super.renderHead(response);
                        body,
                        // <no default value>
                        null);

                // add this method to the class tree
                classDeclaration.defs =
                    classDeclaration.defs.append(methodDef);

                // @formatter:on turn eclipse formatter on again
                this.info(element,
                    "Created renderHead(response) method successfully");

            }
        }

    }
}
于 2010-09-10T08:04:31.677 に答える