【问题标题】:Java: refer to a class variable using a variable [duplicate]Java:使用变量引用类变量[重复]
【发布时间】:2018-07-16 12:02:54
【问题描述】:

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

【问题讨论】:

  • 如果要传递参数,只需使用lovs
  • 看看反射
  • 顺便说一句 Arrays.asList 也是 List
  • 你可以创建 enums 来保存你的字符串,这样你仍然是类型安全的。或者您可以创建一个Supplier&lt;List&lt;String&gt;&gt; 并将其传递给getDropdownValues()
  • A) 遵循 Java 命名约定。您不要在类名中使用 _ 。 B) 常量应该全部大写 C) 当您有一个常量字符串列表时,只需使用 Arrays.asList("A", "B", "C") 创建该列表。当然:那件事应该是最终的。有这么多微妙的低级问题,我想知道您是否真的处于应该开始使用反射的地步。反射是一个高级主题,更重要的是,只有在有充分理由时才使用它。这听起来像是您的设计很糟糕,现在您想使用反射来修复它...

标签: java


【解决方案1】:

您还可以引入一个包含基于名称的引用的 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")

这也会让你的代码被混淆,如果你决定使用反射,这会破坏。

【讨论】:

  • 谢谢,这是我想要的。
【解决方案2】:

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

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

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

称之为

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

【讨论】:

  • 感谢您的回答。但是,当我拨打getDropdownValues(Lists_of_values.circumstances) 时,它是空的...
  • 应该使用类名来限定circumstancesLists_of_values.circumstances
  • @JimmyB 也许,或者你可以做一个静态导入,而且从Lists_of_values本身调用时也不需要它
  • @Alichino circumstances 将在类 Lists_of_values 加载时被初始化,除非它被删除或清空,否则它不能为空
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 2013-04-24
  • 1970-01-01
  • 2021-09-11
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多