javaexception

Howto get the java compiler to insert a variable name into a string


I often find myself writing code like this:

throwExceptionWhenEmpty(fileType, "fileType");
throwExceptionWhenEmpty(channel, "channel");
throwExceptionWhenEmpty(url, "url");

The throwExceptionWhenEmpty method does something like this:

private void throwExceptionWhenEmpty(final String var, final String varName) {
    if (var == null || var.isEmpty()) {
        throw new RuntimeException("Parameter " + varName + " may not be null or empty.");
    }
}

I'd like to avoid this obvious redundancy passing the variable name as string. Is there a way the java compiler can insert the variable name in the string for me?

I'd be happy if I could write something like this:

throwExceptionWhenEmpty(fileType, nameOf(fileType));

Solution

  • No, Java cannot do this until it starts supporting closures which make fields (and methods) first class citizens of the programming language.

    See http://docs.google.com/Doc?id=ddhp95vd_6hg3qhc for an overview on one of the proposals, in which you could do what you want using #field syntax.