gpt4 book ai didi

java - 动态访问Java类的成员变量

转载 作者:行者123 更新时间:2023-12-01 19:33:02 26 4
gpt4 key购买 nike

我有 3 个类,它们具有相同的变量名称,但值不同。因此,我尝试根据用户提供的输入初始化公共(public)对象中的类,然后打印相应的值。

public class A {
public String s1 = "a1";
public String s2 = "a2";
}

public class B {
public String s1 = "b1";
public String s2 = "b2";
}

public class C {
public String s1 = "c1";
public String s2 = "c2";
}

//This is not a working code, just a skeleton to express what I am trying to achieve
public class ClassDriver {
public static void main(String[] args) throws Exception {
String userInput = "A";
//If it's A, then Class A specific values need to be printed at the end
//If it's B, then Class B specific values need to be printed at the end
//If it's C, then Class C specific values need to be printed at the end
Class clazz;
switch(userInput) {
case "A":
clazz = new A();
break;
case "B":
clazz = new B();
break;
case "C":
clazz = new C();
break;
default:
throw new Exception("Not Implemented");
}
System.out.println(clazz.s1);
System.out.println(clazz.s2);
}
}

我不想使用以下反射选项,因为它要求用户将变量名称作为参数传递(在下面的示例中为“s1”),并且它可能不是动态的。

Class aClass = A.class;
Field field = aClass.getField("s1");
System.out.println(field.get(new A()).toString());

我相信应该有其他更好的方法来处理这种情况,但到目前为止我还没有弄清楚。那么有人可以给我一些建议吗?

最佳答案

您可以使用接口(interface)来定义每个类将实现的抽象功能层。

当您创建实现该接口(interface)的类的实例时,您可以确保该类支持该接口(interface)中定义的所需功能子集。

就您而言:

interface MyInterface { // Name this something sensible
public String getS1();
public String getS2();
}

public class A implements MyInterface {
public String getS1() {
return "a1";
}
public String getS2() {
return "a2";
}
}

public class B implements MyInterface {
public String getS1() {
return "b1";
}
public String getS2() {
return "b2";
}
}

稍后在代码中使用时:

...
MyInterface clazz; // Please rename this to something more appropriate
switch(userInput) {
case "A":
clazz = new A();
break;
case "B":
clazz = new B();
break;
case "C":
clazz = new C();
break;
default:
throw new Exception("Not Implemented");
}
System.out.println(clazz.getS1());
System.out.println(clazz.getS2());

关于java - 动态访问Java类的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58978532/

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