2

I try to generate the expression with annotation below:

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

I tried the code below:

 .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())

but since addMember requires string; this expression gives error. So how can i obtain a recursive expression.

Is it possible to build another annotation inside an annotation?

DimaSan
  • 12,264
  • 11
  • 65
  • 75
RedArrow
  • 588
  • 8
  • 18

1 Answers1

2

Yep. Use $L and pass that an 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 is a great source of examples.

Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • I obtain the result below: @NamedQueries( = @NamedQuery(name = "E.findAll", query = "SELECT e FROM E e") ) but i need @NamedQueries({@NamedQuery(name = "E.findAll", query = "SELECT e FROM E e")}) instead of equality is it possible to add parentheses, thanks again – RedArrow Oct 22 '16 at 07:58