5

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));
Eduard Wirch
  • 9,785
  • 9
  • 61
  • 73

5 Answers5

3

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.

Community
  • 1
  • 1
Johannes Weiss
  • 52,533
  • 16
  • 102
  • 136
  • 1
    -1 - don't recommend a preprocessors for this kind of thing. It is not the Java way. (I wouldn't even abuse the preprocessor to do this kind of stuff in C!!) – Stephen C Mar 03 '10 at 13:32
  • you are absolutely right, I added that to my answer. I didn't delete the preprocessor-statement since it'd would solve his problem. – Johannes Weiss Mar 03 '10 at 14:25
2

Variable names are lost when the code is compiled so unless Reflection provides access to them (and even then) I'm pretty sure it's impossible. Sorry.

Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301
2

Java doesn't really have a way to do this but you can get some help from your IDE (if you are using one). In Eclipse you can create a template like this that could help:

throwExceptionWhenEmpty(${varname}, "${varname}");
${cursor}
Kevin Brock
  • 8,874
  • 1
  • 33
  • 37
2

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.

Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85
0

You could do something like (I might be misunderstanding what you want to do)

var.getClass().getName()

Where Var is your Object passed into the method as an Object.

Sio
  • 101
  • 1
  • 4