Generation of switch statement with JavaPoet
Asked Answered
A

1

9

I'm working on a annotation processor written in java. I'm using JavaPoet to generate some lines of code. I have to generate a 'switch' statement. Now i'm using the following code:

MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("parseOnXml")
    .addAnnotation(Override.class)
    .addModifiers(Modifier.PUBLIC)
    .addParameter(typeName(XmlBinderContext.class), "context")
    .addParameter(typeName(XmlWrapperParser.class), "wrapper")
    .addParameter(typeName(Integer.TYPE), "currentEventType")
    .addJavadoc("create new object instance\n")
    .returns(typeName(item.getElement()));

...

methodBuilder.beginControlFlow("switch(eventType)");
methodBuilder.addCode("case $T.START_ELEMENT:\n", XMLEvent.class);
methodBuilder.addStatement("break");
methodBuilder.addCode("case $T.END_ELEMENT:\n", XMLEvent.class);
methodBuilder.addStatement("break");
methodBuilder.addCode("case $T.CDATA:\n", XMLEvent.class);
methodBuilder.addCode("case $T.CHARACTERS:\n", XMLEvent.class);
methodBuilder.addStatement("break");
methodBuilder.addCode("default:\n");
methodBuilder.addStatement("break");
methodBuilder.endControlFlow();

to generate the following code:

switch(eventType) {
    case XMLEvent.START_ELEMENT:
    break;
    case XMLEvent.END_ELEMENT:
    break;
    case XMLEvent.CDATA:
    case XMLEvent.CHARACTERS:
    break;
    default:
    break;
}

Is it the only way to generate a switch statement with javapoet or is there a better way (using beginControlFlow) to generate the same code?

Africa answered 20/11, 2016 at 18:51 Comment(0)
H
5

There's not much in JavaPoet for switch statements so what you have is probably the best you can do. Note that you can use $> and $< to adjust indentation within cases if you like.

Hippogriff answered 20/11, 2016 at 19:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.