I am using JCodemodel to generate java classes dynamically. Below is the code for creating a switch statement whose the default case would be to throw an 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. 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)
));