Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in Java to find the name of the variable that was passed to a function?

Tags:

java

metadata

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.

like image 220
CodeBlue Avatar asked Apr 02 '12 22:04

CodeBlue


People also ask

How do you read a variable from another method in Java?

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).

What is a value passed into a method called in Java?

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.

Can we print variable name in Java?

You can't print just the name of a variable.

How are variables named in Java?

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 " _ ".


2 Answers

Consider that the parameter might not have been a variable (and therefore wouldn't have a name):

testForNull(x != y);
like image 116
Oliver Charlesworth Avatar answered Oct 07 '22 19:10

Oliver Charlesworth


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.

like image 40
Vincent Cantin Avatar answered Oct 07 '22 20:10

Vincent Cantin