我正在使用 JCodemodel 动态生成 java 类。下面是创建 switch 语句的代码,其默认情况是抛出异常。
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)
));
关于java - JCodemodel 中的异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42444827/