gpt4 book ai didi

JAVA 获取类中的实例名称?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:44:04 25 4
gpt4 key购买 nike

假设我有以下类(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:负担得起

最佳答案

如上所述,如果实例名称对您如此重要,请重新定义您的类

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

关于JAVA 获取类中的实例名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29524276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com