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

4
  • I cannot change the source of DummyClass. Commented Dec 17, 2010 at 0:36
  • 1
    I would look into using reflection. Commented Dec 17, 2010 at 0:38
  • 1
    Can you make it an enum? Commented Dec 17, 2010 at 1:12
  • @Tom As I said, I do not have access to source file. Commented Dec 17, 2010 at 2:10

2 Answers 2

47

You could use reflection:

Field[] fields = DummyClass.class.getDeclaredFields();
for (Field f : fields) {
    if (Modifier.isStatic(f.getModifiers()) && isRightName(f.getName())) {
        doWhatever(f);
    } 
}
Sign up to request clarification or add additional context in comments.

5 Comments

@Chandra Please mark an aswer correct, if you think its correct solution
@Cameron I don't find any isRghtName() method in the Modifier class.
@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.
Should the && really be inside the isStatic-method? If so there are still two ) missing in the if statement.
@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) { }
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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.