Getting all static variables in a class to an array / list

A bit of the simplest 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 this class, can we combine this var into a single array or list so that I can iterate over them? For example, if I do something like

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

I must have access to var1 ... var100

+13
source share
2 answers

You can use reflection:

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

If you have a class with constants and want to get the actual values ​​of your java constant, you can do the 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());
0
source

All Articles