Java:使用变量引用类变量

时间:2018-07-16 12:02:55

标签: java

文件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")

2 个答案:

答案 0 :(得分:4)

您还可以引入一个Map,该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")

这也将使您的代码变得模糊,如果您决定使用反射,则代码将中断。

答案 1 :(得分:1)

不,您不能(除非您使用反射API)

正确的方法是将适当的列表传递给getDropdownValues

public String getDropdownValues(List<String> list) {
    String templovList = StringUtils.join(list, ' ');
    return templovList;
}

命名为

getDropdownValues(circumstances); //or getDropdownValues(interruptions);