我正在使用JCodemodel动态生成Java类。以下是用于创建switch语句的代码,该语句的默认情况是引发Exception。

JSwitch valueswitch;

AbstractJClass exception = ref(IllegalArgumentException.class);

valueswitch._default()
          .body()
          ._throw(JExpr._new(exception));


生成的类如下所示

public static Example switchCode(String code) {
        switch (code) {
            case "1":
            {
                return A;
            }
            default:
            {
                throw new IllegalArgumentException();
            }
        }
    }


现在我想向抛出的异常添加一条消息,例如

throw new IllegalArgumentException("Invalid code "+ code);


我如何在JCodemodel中实现这一目标。任何帮助,将不胜感激。

最佳答案

您只需要将语句添加到异常构造函数中即可:

    valueswitch._default()
            .body()
            ._throw(JExpr._new(exception)
                    .arg(
                            JOp.plus(JExpr.lit("Invalid code "), codeParam)
                    ));

09-05 03:41