gpt4 book ai didi

JavaPoet:如何在注释中构建注释

转载 作者:行者123 更新时间:2023-11-30 10:37:17 24 4
gpt4 key购买 nike

我尝试生成带有注释的表达式:

@NamedQueries({@NamedQuery(name = "E.findAll", query = "SELECT e FROM E e")})

我尝试了下面的代码:

 .addAnnotation(AnnotationSpec.builder(NamedQueries.class)        
.addMember( AnnotationSpec.builder(NamedQuery.class)
.addMember("name", "$S", "E.findAll")
.addMember("query", "$S", "SELECT e FROM E e)
.build()).build())

但是因为 addMember 需要字符串;这个表达式给出了错误。那么我怎样才能得到一个递归表达式。

是否可以在注释中构建另一个注释?

最佳答案

是的。使用 $L 并传递一个 AnmotationSpec。

ClassName beef = ClassName.get(tacosPackage, "Beef");
ClassName chicken = ClassName.get(tacosPackage, "Chicken");
ClassName option = ClassName.get(tacosPackage, "Option");
ClassName mealDeal = ClassName.get(tacosPackage, "MealDeal");
TypeSpec menu = TypeSpec.classBuilder("Menu")
.addAnnotation(AnnotationSpec.builder(mealDeal)
.addMember("price", "$L", 500)
.addMember("options", "$L", AnnotationSpec.builder(option)
.addMember("name", "$S", "taco")
.addMember("meat", "$T.class", beef)
.build())
.addMember("options", "$L", AnnotationSpec.builder(option)
.addMember("name", "$S", "quesadilla")
.addMember("meat", "$T.class", chicken)
.build())
.build())
.build();
assertThat(toString(menu)).isEqualTo(""
+ "package com.squareup.tacos;\n"
+ "\n"
+ "@MealDeal(\n"
+ " price = 500,\n"
+ " options = {\n"
+ " @Option(name = \"taco\", meat = Beef.class),\n"
+ " @Option(name = \"quesadilla\", meat = Chicken.class)\n"
+ " }\n"
+ ")\n"
+ "class Menu {\n"
+ "}\n");

This test是一个很好的示例来源。

关于JavaPoet:如何在注释中构建注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40185593/

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