4

Suppose I have the following class:

public class System {

  private String property1;
  private String property2;
  private String property3;

  public void showProperties {
      System.out.println("Displaying properties for instance "+<INSTANCE NAME>+"of object System:"
                         "\nProperty#1: " + property1 +
                         "\nProperty#2: " + property2 +
                         "\nProperty#3: " + property3);
}

I'm looking for a way to get the name of the System-instance that will be calling the method showProperties, so that when writing:

System dieselEngine= new System();
mClass.property1 = "robust";
mClass.property2 = "viable";
mClass.property3 = "affordable";
dieselEngine.showProperties();

The console output would be:

Displaying properties for instance dieselEngine of object 'System':

Property#1: robust

Property#2: viable

Property#3: affordable

Răzvan Barbu
  • 189
  • 4
  • 16
  • You are trying to get the variable name? As far as I know this can't be done (easily) with Java – Kon Apr 08 '15 at 20:02
  • 1
    I think that if the name is important, it should be an instance attribute. What would you do if you had two variables referecing the same object? – Anderson Vieira Apr 08 '15 at 20:04
  • 6
    Instances (objects) do not have a name. Variables have a name. A variable is not an object - it contains a *reference* to an object. Multiple variables may refer to the same object. So, there is no such thing as an "instance name" that you can get from an object. – Jesper Apr 08 '15 at 20:04
  • It is kind of complicated, but it's what they're talking about here: http://stackoverflow.com/questions/744226/java-reflection-how-to-get-the-name-of-a-variable – theguywhodreams Apr 08 '15 at 20:05
  • If you need this, you need to make the name a field in your class. `Component` is an example of where this is implemented in the J2SE. Also, variable names in all Java methods disappear on compilation. – ControlAltDel Apr 08 '15 at 20:11
  • @Jesper thank you for the remark. I do believe, however, that the explanation I provided alongside my question was comprehensive enough in order to suggest a solution. – Răzvan Barbu Apr 08 '15 at 20:21
  • What you are asking, as stated, is simply not possible, because an object doesn't have a name by itself. One way is to add it yourself as a field in the class, as in Sai Phani's answer. – Jesper Apr 08 '15 at 20:25
  • Note that you will also get a problem because you named your class `System`, the same as the standard class `java.lang.System`. The line `System.out.println(...)` is going to give you a compiler error, because your class `System` doesn't have a member named `out`. – Jesper Apr 08 '15 at 20:31
  • @Jesper Yes, you are correct. Nevertheless, my problem did not regard syntax perfection (might as well have forgotten a semicolon), but grasping the concept of return a variable name. – Răzvan Barbu Apr 08 '15 at 20:41
  • My comments have nothing to do with syntax. An object doesn't know the variable(s) that are referring to it. So you can't get to those variables from the object, and also not the names of those variables. – Jesper Apr 08 '15 at 20:43

2 Answers2

5

As told above if instance name is so important to you, redefine your class

class System {
    private String property1;
    private String property2;
    private String property3;
    private String instanceName;

    public System (String instance){
        instanceName = instance;
    }

    public void showProperties() {
        java.lang.System.out
            .println("Displaying properties for instance of "+instanceName+"object System:"
                    + "\nProperty#1: " + property1 + "\nProperty#2: "
                    + property2 + "\nProperty#3: " + property3);
    }
}

and assign while creating object

your.class.path.System dieselEngine= new your.class.path.System("dieselEngine");

Working Example

martinez314
  • 12,162
  • 5
  • 36
  • 63
Sai Phani
  • 259
  • 1
  • 6
  • I like this answer, but the code originally shown above didn't match the **Working Example** and didn't compile when I tried it. I've modified two lines and commented the originals so that the code works and conforms to the referenced example. – CODE-REaD Jun 23 '16 at 18:09
3

Here an hint snippet that I just wrote using java.lang.reflect.Field

public class Test
{
    int a, b, c;

    Test d;//Your type will be System here (System dieselEngine)

    public static void main(String args[])
    {
        for(Field f : Test.class.getDeclaredFields())
        {
            if(f.getType() == Test.class)//Here you would retrieve the variable name when the type is dieselEngine.
                System.out.println(f.getName());
        }

    }
}

From here, you should be able to achieve what you want.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • This is not correct, a Field is an internal structure inside a Class (a property) and not the variable name as the OP wants. Also, this is available in Java 7. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html – Necreaux Apr 08 '15 at 20:22
  • @Necreaux If you read my post properly (including the comments) you will realize that this will retrieve the fields of the class, then I filter by the wanted type and retrieve the name. As for the version you are right. I edited. – Jean-François Savard Apr 08 '15 at 20:24
  • It will only work if the class the OP wants the variable name for is a property inside another class, and then you would need to know the parent class. This only works in VERY limited cases, and not in your sample: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getDeclaredFields() – Necreaux Apr 08 '15 at 20:26
  • @Necreaux This is false, try running my sample. – Jean-François Savard Apr 08 '15 at 20:27
  • thx @Jean-FrançoisSavard . it works as a charm – max Mar 27 '21 at 10:44
  • @Jean-FrançoisSavard is it possible to get the instance name not from the field, but from the **psvm**? – max Mar 27 '21 at 10:55