Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 401
Eduard Wirch Avatar asked Mar 03 '10 13:03

Eduard Wirch


People also ask

Can we get variable name in Java?

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.

Can we use string as a variable name in Java?

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.

How do you call a method with a variable name in Java?

String MyVar=2; MethodMyVar();


1 Answers

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.

like image 84
Johannes Weiss Avatar answered Oct 07 '22 06:10

Johannes Weiss