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?
JavaPoet is developed by Square, which provides APIs to generate Java source code. It can generate primitive types, reference types and their variants (such as classes, interfaces, enumerated types, anonymous inner classes), fields, methods, parameters, annotations, and Javadocs.
An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.
The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
Yes, and just like that.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With