JAVA获取类中的实例名称?

时间:2015-04-08 20:01:16

标签: java instance

假设我有以下课程:

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

控制台输出将是:

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

属性#1:健壮

属性#2:可行

物业#3:负担得起

2 个答案:

答案 0 :(得分:5)

如上所述,如果实例名称对您来说非常重要,请重新定义您的班级

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

答案 1 :(得分:1)

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

    }
}

从这里开始,你应该能够实现你想要的目标。