简体   繁体   中英

Exception message in JCodemodel

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM