gpt4 book ai didi

java - 为使用 Javassist 创建的新方法的参数添加注释

转载 作者:行者123 更新时间:2023-11-29 09:10:39 31 4
gpt4 key购买 nike

我需要为方法参数添加注释。该方法之前是使用 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) 找到这个 solution但它基于在我的例子中返回 null 的行:

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

我不知道如何完成这个;有没有人找到一种方法来创建新方法并为其参数添加任何注释?

提前致谢。

最佳答案

根据我在原始问题中提到的解决方案找到了解决方法。我无法创建类,无法向其添加方法并使用 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 的名称。它不像预期的那样灵活,但至少可以通过这样的方法解决某些场景。欢迎任何其他解决方法!

关于java - 为使用 Javassist 创建的新方法的参数添加注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12625697/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com