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.
rf1is 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: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 aNamemember and initialize the name in the constructor:Here, the name of the object is “myname”. Not
rf1, which is the name of the variable.