Can I get the name of the current link in Java?

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, can I do this in Java?

thanks.

+4
source share
6 answers

rf1 is just a variable name, so even if you can do it, it will not be a class method. In the end, you could:

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

it is the same instance ; What should rf1.outRefName() produce? No, I don’t think you can do it. In C # there are some hacker ways to do this (involving captured variables and checking the reflection or expression tree), but again - you get the variable name - nothing to do with the object. A better approach here might 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.

+3
source

Unable to execute. What will print as follows?

 RefName a = new RefName(), b; (b = a).outRefName(); 
+3
source

If this information is meaningful, you need to pass this information on yourself .

 public class RefName { private String name; public RefName(String name) { this.name = name; } public String outRefName() { System.out.println(name); } } 

-

 RefName rf1 = new RefName("rf1"); rf1.outRefName(); 
+2
source

Imagine that we are colleagues, and when I mention you about my family members, we use some kind of nickname. Let me say: "The other day, my high colleague said this." You do not need to know how we call you. Is not it?

+1
source

This cannot be done in Java. I think you can clearly understand why here:

 (new RefName()).outRefName() 

"Link" did not even get a name.

+1
source

Using Reflection, you can find which fields of the object contain this instance. This only works for fields, not for variables. Here's an incomplete sample:

 public class BackRef { private class RefName { // finds first field containing this object public String outRefName() { Field[] fields = BackRef.class.getDeclaredFields(); for (Field field : fields) { if (getClass().isAssignableFrom(field.getType())) { field.setAccessible(true); try { if (field.get(BackRef.this) == this) return field.getName(); } catch (Exception ex) { ex.printStackTrace(); } } } return null; } } private RefName ref1; private RefName ref2; BackRef() { ref1 = new RefName(); ref2 = new RefName(); System.out.println(ref1.outRefName()); System.out.println(ref2.outRefName()); } public static void main(String[] args) { new BackRef(); } } 

This is a kind of (big) hack, but I used it once to display in which field the GUI component was saved with a click ...

+1
source

All Articles