18

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

Chandra
  • 777
  • 3
  • 12
  • 18

2 Answers2

47

You could use reflection:

Field[] fields = DummyClass.class.getDeclaredFields();
for (Field f : fields) {
    if (Modifier.isStatic(f.getModifiers()) && isRightName(f.getName())) {
        doWhatever(f);
    } 
}
Cameron Skinner
  • 51,692
  • 2
  • 65
  • 86
  • 1
    @Chandra Please mark an aswer correct, if you think its correct solution – Ratna Dinakar Dec 17 '10 at 01:07
  • @Cameron I don't find any isRghtName() method in the Modifier class. – Naruto Uzumaki Jun 06 '13 at 09:38
  • 3
    @NarutoUzumaki: It's pseudocode. `isRightName` is meant to signify user code that decides if the field name is interesting. Note that this snippet does not call `Modifier.isRightName`; it's just `isRightName`. – Cameron Skinner Jun 06 '13 at 22:54
  • Should the `&&` really be inside the `isStatic`-method? If so there are still two `)` missing in the if statement. – jmattheis Jul 24 '17 at 07:35
  • @CameronSkinner how I can make it to a genenal util method for all this kind of Classes, I tried pass DummyClass as a parameter that argument is a type of class? but not worked. thx. code is something like: `public void printAllProps(Class c) { }` – neifnei Jul 30 '20 at 14:22
3

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());
walkeros
  • 4,736
  • 4
  • 35
  • 47