簡體   English   中英

JAVA獲取類中的實例名稱?

[英]JAVA Get Name of Instance inside 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-instance的名稱,以便在編寫時:

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

控制台輸出將是:

顯示 對象'System'的 例子 dieselEngine 的屬性:

財產#1:強大

財產#2:可行

物業#3:價格實惠

如上所述,如果實例名稱對您來說非常重要,請重新定義您的課程

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");

工作實例

這里是我剛剛使用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());
        }

    }
}

從這里,你應該能夠實現你想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM