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?