tags:

views:

134

answers:

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));
+3  A: 

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.

Johannes Weiß
-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
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 Weiß
+2  A: 

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
This is why I asked for compiler substitution.
Eduard Wirch
Oh yeah, I see. Well I don't think any well known compiler can do it, but maybe a code preprocessor? Of course, they're often nastier than the problem you're trying to solve.
Bart van Heukelom
+2  A: 

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
A: 

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
+2  A: 

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