如何使用javapoet读取方法参数的注释
我试图通过阅读带注释的方法生成代码,如如何使用javapoet读取方法参数的注释,java,annotations,annotation-processing,javapoet,Java,Annotations,Annotation Processing,Javapoet,我试图通过阅读带注释的方法生成代码,如 @MyAnnotation public static int generatorMethod(@SomeOtherAnnotation Boolean someArg) 我想复制参数列表,因为它们在生成的代码中 如下图所示: public class MyGeneratedClass{ public int myGeneratedMethod(@SomeOtherAnnotation Boolean someArg) { //
@MyAnnotation
public static int generatorMethod(@SomeOtherAnnotation Boolean someArg)
我想复制参数列表,因为它们在生成的代码中
如下图所示:
public class MyGeneratedClass{
public int myGeneratedMethod(@SomeOtherAnnotation Boolean someArg) {
//method body
}
}
但当我试图从annotationProcessor类中读取带注释的方法时
for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
messager.printMessage(
Diagnostic.Kind.NOTE, String.format("Annotated Element as string: %s",
annotatedElement.toString()));
}
它将值打印为
Annotated Element as string: generatorMethod(java.lang.Boolean)
它没有引用参数的注释,我可以用它来创建ParameterSpec
有没有一种方法可以读取参数的注释?(这似乎与JavaPoet无关,JavaPoet用于将详细信息写入新的java文件,而不是读取类型的详细信息。)
实际上,Element.toString()方法仅在调试时才有意义——APT api的不同实现(例如Eclipse的JDT)返回不同的值。打印方法的完整描述不是一种有效的方法,它还需要包含返回类型,无论是final/abstract/native/public/private/等等
而是从元素(可执行元素)实例中读取有关该方法的详细信息。如果您试图使用JavaPoet创建方法,那么应该使用MethodSpec生成器,并将元素中的每个细节传递到生成器中以创建方法规范
如上所述,由于这是一个方法,因此它是一个可执行元素
,具有读取参数(和类型参数)以及检查方法是否为varargs参数等的特定方法
然后,每个参数将是一个可变元素
,它也从元素
扩展而来,因此您可以读取其上的注释。可能的重复: