JAVA 获取 Class 中的实例名称?

JAVA Get Name of Instance inside Class?

假设我有以下 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);
}

我正在寻找一种方法来获取将调用方法 showProperties 的系统实例的名称,以便在编写时:

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

控制台输出为:

显示对象'System'的实例dieselEngine的属性:

属性#1:健壮

属性#2:可行

属性#3:负担得起

这是我刚刚使用 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());
        }

    }
}

从这里开始,你应该可以实现你想要的。

如上所述,如果实例名称对您如此重要,请重新定义您的 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);
    }
}

并在创建对象时赋值

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

Working Example