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));
For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word. Variables in Java are not allowed to contain white space, so variables made from compound words are to be written with a lower camel case syntax.
In Java, there are different types of variables, for example: String - stores text, such as "Hello". String values are surrounded by double quotes. int - stores integers (whole numbers), without decimals, such as 123 or -123.
String MyVar=2; MethodMyVar();
That should answer your question: SO: How to get name of a variable.
It's not (easily) possible in Java.
You could use a preprocessor and integrate it in your build process. That would probably be very simple and portable. But as Stephen C said in the comments section, that's really not the Java way and is therefore not recommended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With