Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA Get Name of Instance inside Class?

Tags:

java

instance

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

like image 264
Răzvan Barbu Avatar asked Feb 10 '23 11:02

Răzvan Barbu


1 Answers

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

like image 73
Sai Phani Avatar answered Feb 13 '23 03:02

Sai Phani