Răzvan Barbu
Răzvan Barbu

Reputation: 189

JAVA Get Name of Instance inside Class?

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

Upvotes: 4

Views: 9204

Answers (2)

Sai Phani
Sai Phani

Reputation: 259

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

Upvotes: 5

Jean-Fran&#231;ois Savard
Jean-Fran&#231;ois Savard

Reputation: 21004

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.

Upvotes: 3

Related Questions