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