8

我正在研究用java编写的注释处理器。我正在使用 JavaPoet 生成一些代码行。我必须生成一个'switch'语句。现在我正在使用以下代码:

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();

生成以下代码:

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

它是使用 javapoet 生成 switch 语句的唯一方法还是有更好的方法(使用 beginControlFlow)来生成相同的代码?

4

1 回答 1

4

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.

于 2016-11-20T19:04:51.423 回答