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