Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generation of switch statement with JavaPoet

Tags:

java

javapoet

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?

like image 866
xcesco Avatar asked Nov 20 '16 18:11

xcesco


People also ask

What is JavaPoet?

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.

When to use switch vs if Java?

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.

What data TypeS can be used in a switch statement Java?

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.

Can we use if statement in switch case in Java?

Yes, and just like that.


1 Answers

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.

like image 116
Jesse Wilson Avatar answered Oct 12 '22 21:10

Jesse Wilson