[kotlinpoet] hello! I’m trying to annotate my clas...
# squarelibraries
d
[kotlinpoet] hello! I’m trying to annotate my class with nested interface but I’m having trouble with it -> trying to create following Jackson annotations
Copy code
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "__typename")
@JsonSubTypes(value = [
    Type(value = Car::class, name = "Car"),
    Type(value = Plane::class, name = "Plane")])
interface Vehicle {
I’m getting pretty close but am unsure how to generate the
JsonSubTypes
values, e.g.
Copy code
interfaceTypeSpec.addAnnotation(AnnotationSpec.Companion.builder(JsonTypeInfo::class.java)
    .addMember("use = %T", JsonTypeInfo.Id.NAME::class.java)
    .addMember("include = %T", JsonTypeInfo.As.PROPERTY::class.java)
    .addMember("property = %S", "__typename")
    .build())
// implementations is a list of ClassName
val jsonSubTypes = implementations.map { implementationType ->
    AnnotationSpec.builder(JsonSubTypes.Type::class.java)
        .addMember("value = %T::class", implementationType)
        .addMember("name = %S", implementationType.simpleName)
        .build()
}
interfaceTypeSpec.addAnnotation(AnnotationSpec.Companion.builder(JsonSubTypes::class.java)
    .addMember("value = %L", jsonSubTypes)
    .build())
this generates
Copy code
@JsonTypeInfo(
    use = JsonTypeInfo.Id,
    include = <http://JsonTypeInfo.As|JsonTypeInfo.As>,
    property = "__typename"
  )
  @JsonSubTypes(value = [@com.fasterxml.jackson.annotation.JsonSubTypes.Type(value =
     path.to.Car::class,
      name = "Car"),
      @com.fasterxml.jackson.annotation.JsonSubTypes.Type(value =
      path.to.Plane::class,
      name = "Plane")])
  interface Vehicle
the problem is that I cannot use annotations as values for another annotation
any ideas?
guess I manually create code block ->
Copy code
val jsonSubTypesCodeBlock = CodeBlock.builder()
implementations.forEach { implClassName ->
    if (jsonSubTypesCodeBlock.isNotEmpty()) {
        jsonSubTypesCodeBlock.add(",")
    }
    jsonSubTypesCodeBlock.add("com.fasterxml.jackson.annotation.JsonSubTypes.Type(value = %T::class, name=%S)", implClassName, implClassName.name)
}
seems pretty hacky though
e
%L
should work for `AnnotationSpec`s
d
Well it generates annotation spec with '@' which cannot be used as value for another annotation
e
Oh, I see. Yeah, creating a code block manually is probably the only way to do it.