getting all static variables in a class into array/list

笑着哭i 提交于 2019-12-20 18:23:20

问题


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

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

I should be able to access var1...var100


回答1:


You could use reflection:

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



回答2:


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

   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());


来源:https://stackoverflow.com/questions/4466743/getting-all-static-variables-in-a-class-into-array-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!