I have a Java function called testForNull
public static void testForNull(Object obj)
{
if (obj == null)
{
System.out.println("Object is null");
}
}
I use it to test multiple objects to ensure they are not null. But, I am unable to tell the name of the variable that way.
For eg. if I say
testForNull(x);
testForNull(y);
testForNull(z);
I cannot tell which of the three lines caused the "Object is null" output. Of course, I can simply add another parameter to the function and have something like
testForNull(x, "x");
testForNull(y, "y");
testForNull(z, "z");
But I want to know whether it is possible to deduce the name of the variable without passing it explicitly. Thanks.
You can't. Variables defined inside a method are local to that method. If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.
You can't print just the name of a variable.
A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign " $ ", or the underscore character " _ ". The convention, however, is to always begin your variable names with a letter, not " $ " or " _ ".
Consider that the parameter might not have been a variable (and therefore wouldn't have a name):
testForNull(x != y);
No, there is no such a way. You will have to explicitly pass the name of the variable.
However, if your object has a field 'name' or displays its name via the toString()
function, then that might help you.
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