3

メソッドパラメータにアノテーションを追加する必要があります。このメソッドは、以前は次のようなjavassistで作成されていました。

CtClass cc2 = pool.makeClass("Dummy");
CtMethod method = CtNewMethod.make("public java.lang.String dummyMethod( java.lang.String oneparam){ return null; }", cc2);

追加したい注釈は非常に単純です。

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)

public @interface Param {
    /** Name of the parameter */
    String name() default "";
}

1)メソッド作成でアノテーションを書くとスロー

javassist.CannotCompileException: [source error] syntax error near "myMethod(@Param

2)この解決策を見つけましたが、私の場合はnullを返す行に基づいています:

AttributeInfo paramAtrributeInfo = methodInfo.getAttribute(ParameterAnnotationsAttribute.visibleTag); // or inVisibleTag

私はこれを達成する方法に迷っています。新しいメソッドを作成し、そのパラメーターにアノテーションを追加する方法を見つけた人はいますか?

前もって感謝します。

4

1 に答える 1

1

元の質問で述べた解決策に基づいて回避策を見つけました。クラスを作成できず、それにメソッドを追加して、javassistを使用してそのパラメーターにアノテーションを挿入できませんでした。ただし、実際のクラスをテンプレートとして使用すると、パラメーターの注釈を見つけて編集できます。

1)まず、目的のアノテーションを持つメソッドを使用してクラスを作成します

public class TemplateClass {
    public String templateMethod(@Param String paramOne) {
        return null;
    }
}

2)それをロードします

ClassPool pool = ClassPool.getDefault();
CtClass liveClass = null;
try {
     liveClass = pool.get("your.package.path.Dummyclass");
} catch (NotFoundException e) {
     logger.error("Template class not found.", e);
}

3)それを働かせる

// -- Get method template
    CtMethod dummyMethod = liveClass.getMethods()[2];
    // -- Get the annotation
    AttributeInfo parameterAttributeInfo = dummyMethod.getMethodInfo().getAttribute(ParameterAnnotationsAttribute.visibleTag);
    ConstPool parameterConstPool = parameterAttributeInfo.getConstPool();
    ParameterAnnotationsAttribute parameterAtrribute = ((ParameterAnnotationsAttribute) parameterAttributeInfo);
    Annotation[][] paramArrays = parameterAtrribute.getAnnotations();
    Annotation[] addAnno = paramArrays[0];
    //-- Edit the annotation adding values
    addAnno[0].addMemberValue("value", new StringMemberValue("This is the value of the annotation", parameterConstPool));
    addAnno[0].addMemberValue("required", new BooleanMemberValue(Boolean.TRUE, parameterConstPool));
    paramArrays[0] = addAnno;
    parameterAtrribute.setAnnotations(paramArrays);

次に、結果クラスを作成する前に、CtClassやCtMethodの名前を変更します。期待したほど柔軟ではありませんが、少なくともいくつかのシナリオはこのようなアプローチで解決できます。他の回避策は大歓迎です!

于 2012-10-02T14:13:47.187 に答える