I don't know if this question is well worded but here is the question.
I have my class ProductosLacteos
. When I create the instance I do this:
ProductosLacteos quesito = new ProductosLacteos();
So I want to get quesito
as a text string. So that? Debugging issue. I have a console where different program data is displayed, but the plan is that inside I ProductosLacteos
can access the instance name with getNombreDeLaInstancia()
. This is what I expect:
ProductosLacteos quesito = new ProductosLacteos();
ProductosLacteos lechita = new ProductosLacteos();
ProductosLacteos jocoque = new ProductosLacteos();
System.out.println(quesito.getNombreDeLaInstancia());
System.out.println(lechita.getNombreDeLaInstancia());
System.out.println(jocoque.getNombreDeLaInstancia());
And I get the result:
"cheese"
"little milk"
"jocoque"
Will it be possible to access this data extends
in such a way that I have it available for all my classes?
Thank you!
The instance has no "name".
What you see is a reference , which directs you to what the instance itself is. But the reference name is just so you can use it to compile your program (instead of, say, using the stackpointer value plus an offset). For example, the compiled code does not keep the name of local variables, it is completely unaware of it.
To illustrate, think about what you do:
Now the two references point to the same instance. What is the "name" of this one?
If you want to identify an instance of a class by an attribute, include that attribute inside the class and give it a value. For example:
Now you can get the "name" by accessing the property (via a getter ). You can also reimplement
toString
, and maybeequals
andhashCode
, relative to it.The name of the variable is just the identifier of the memory space, the instance of an object does not have a name itself, it could have a property but it would not serve your idea unless the property stores the variable name of the object.
As of Java 8 you can make use of reflection.
use:
import java.lang.reflect.Field;
.getName()
Note: a is used
String
because I don't have that class, and not to make the example longer, the class is usedString
because it is the simulation of theirs, but it should work just the same.Test:
Ideone