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) 在方法创建中写注解 throws

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 回答