gpt4 book ai didi

Java:使用变量引用类变量

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

文件Lists_of_values.java :

public class Lists_of_values {
public static List<String> circumstances = new ArrayList<String>(Arrays.asList("Medical", "Maternity", "Bereavement", "Other"));
public static List<String> interruptions = new ArrayList<String>(Arrays.asList("Awaiting results", "Courses not available", "Fieldwork",
"Health reasons", "Internship with stipend", "Other"));
}

文件Main_file.java :

public String getDropdownValues(String lovs) {
String templovList = StringUtils.join(Lists_of_values.lovs, ' ');
return templovList;
}

这给了我:lovs cannot be resolved or is not a field

有没有办法在 getDropdownValues 中使用此上下文中的变量作为参数?这样我就可以调用 getDropdownValues("circumstances") .

最佳答案

您还可以引入一个包含基于名称的引用的 Map:

import java.util.*;

public class Lists_of_values {
public static List<String> circumstances = Arrays.asList("Medical", "Maternity", "Bereavement", "Other");
public static List<String> interruptions = Arrays.asList("Awaiting results", "Courses not available", "Fieldwork", "Health reasons", "Internship with stipend", "Other");

private static Map<String, List<String>> lists = new HashMap<>();
static {
lists.put("circumstances", circumstances);
lists.put("interruptions", interruptions);
}

public static List<String> getList(String name) {
return lists.get(name);
}
}

这将用作:List_of_Values.getList("circumstances")

这也会使您的代码被混淆,如果您决定使用反射,这就会中断。

关于Java:使用变量引用类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51361400/

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