gpt4 book ai didi

java - 判断变量是否在类中声明

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

我有一个类,比如测试;其中有一个嵌套的静态类,例如 TestParams。

TestParams仅包含一些引用Test类的字符串变量

我面临的问题是,在 Test 类的 setter 中,我需要验证设置的参数是否是 Params 类中声明的参数之一。

该场景如下面的代码所示:

public class Test {

protected String n;
protected int num;

public static class TestParams {
public static final String PARAM_N="n";
public static final String PARAM_NUM="num";
}

public void setParam(String key, Object value) {
// Need to check here the if key is defined in TestParams
// keep adding conditions to IF statement when more params added??
if(key.equals(TestParams.PARAM_N) || (key.equals(TestParams.PARAM_NUM))
// Do some stuff
}

}

有没有办法用多个条件替换IF语句? (类似于 if key in TestParams() 或者代码结构的其他设计?

最佳答案

为了解决您所询问的特定问题,除了使用反射之外,我没有其他方法:

private boolean isValidKey(String str) {
for (Field f : TestParams.class.getFields())
try {
if (f.get(null).equals(str))
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

尽管我强烈鼓励您重新考虑设计。

关于java - 判断变量是否在类中声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26235158/

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