Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could I get the name of current reference within Java?

Tags:

java

reference

public class RefName { 
  void outRefName() {
    System.out.println("the current reference name is" + xxx);
  };
};

public static void main(String[] args) {
  RefName rf1 = new RefName();
  rf1.outRefName();   // should be rf1
  RefName rf2 = new RefName();
  rf2.outRefName();   // should be rf2
};

As the code above shows,could I make this happen within Java?

thanks.

like image 280
Jichao Avatar asked Dec 18 '22 04:12

Jichao


1 Answers

rf1 is just the name of the variable, so even if you could get this working, it would not be a method of the class - after all, you could have:

RefName rf1 = new RefName();
RefName rf2 = rf1;

this is the same instance; what should rf1.outRefName() produce? No, I don't think you can do this. In C# there are some hacky ways of doing it (involving captured variables and either reflection or expression-tree inspection), but again - you are getting the variable name - nothing to do with the object. The better approach here may be to give your class a Name member and initialize the name in the constructor:

RefName rf1 = new RefName("myname");

Here, the name of the object is "myname". Not rf1, which is the name of the variable.

like image 62
Marc Gravell Avatar answered Jan 26 '23 00:01

Marc Gravell