java 将类中的所有静态变量放入数组/列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4466743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:31:20  来源:igfitidea点击:

getting all static variables in a class into array/list

javaarraysarraylist

提问by Chandra

Bit of a wierd requirement.

有点奇怪的要求。

public class DummyClass{
   public static final DummyClass var1;
   public static final DummyClass var2;
   public static final DummyClass var3;
    .
    .
    .
   public static final DummyClass var100;
}

Now from outside of this class can we pool this var's into a single array or list, so that I can iterate over them? Like if i do something like

现在从这个类的外部,我们可以将这个 var 合并到一个数组或列表中,以便我可以迭代它们吗?就像如果我做类似的事情

List<DummyClass> dummyList = *some op*; //I want value of some op.

I should be able to access var1...var100

我应该能够访问 var1...var100

回答by Cameron Skinner

You could use reflection:

你可以使用反射:

Field[] fields = DummyClass.class.getDeclaredFields();
for (Field f : fields) {
    if (Modifier.isStatic(f.getModifiers()) && isRightName(f.getName())) {
        doWhatever(f);
    } 
}

回答by walkeros

If you have a class with constants and want to get the actual values of your java constant you can do following:

如果您有一个带有常量的类并想要获取 Java 常量的实际值,您可以执行以下操作:

   List<String> constantValues = Arrays.stream(DummyClass.class.getDeclaredFields())
      .filter(field -> Modifier.isStatic(field.getModifiers()))
      .map(field -> {
        try {
          return (String) field.get(DummyClass.class);
        } catch (IllegalAccessException e) {
          throw new RuntimeException(e);
        }
      })
      .filter(name -> ! name.equals("NOT_NEEDED_CONSTANT") // filter out if needed 
      .collect(Collectors.toList());