[英]Exception message in JCodemodel
I am using JCodemodel to generate java classes dynamically. 我正在使用JCodemodel动态生成Java类。 Below is the code for creating a switch statement whose the default case would be to throw an Exception.
以下是用于创建switch语句的代码,该语句的默认情况是引发Exception。
JSwitch valueswitch;
AbstractJClass exception = ref(IllegalArgumentException.class);
valueswitch._default()
.body()
._throw(JExpr._new(exception));
The generated class looks like below 生成的类如下所示
public static Example switchCode(String code) {
switch (code) {
case "1":
{
return A;
}
default:
{
throw new IllegalArgumentException();
}
}
}
Now I want to add a message to the exception thrown like 现在我想向抛出的异常添加一条消息,例如
throw new IllegalArgumentException("Invalid code "+ code);
How can i achieve this in JCodemodel. 我如何在JCodemodel中实现这一目标。 Any help would be appreciated.
任何帮助,将不胜感激。
You simply need to add the statement to the exception constructor: 您只需要将语句添加到异常构造函数中即可:
valueswitch._default()
.body()
._throw(JExpr._new(exception)
.arg(
JOp.plus(JExpr.lit("Invalid code "), codeParam)
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.