4

My question is: how to create a list of all constants of specified class?

Is this possible in an easy way? Or I just need to write my own (somewhat simple) solution for this?

Let me present some code:

public class StateOfSomeProcess {
    private final static String STATE_A = "State A";
    private final static String STATE_B = "State B";
    private final static String STATE_C = "State C";
    private final static String STATE_D = "State D";

    public StateOfSomeProcess() {...}

    public List<String> getListOfAllStates() {
        List<String> list = new ArrayList<String>();
        ...
        //I wish there was a method like this:
        //list = this.getAllConstantsFromClass();
        ...
        return list;
    }
}

I know about enums, but it does not seem to fit my needs. Please feel free to let me know if my question is unclear or needs improvement.

bercik
  • 164
  • 12
  • 2
    Are you familiar with the concept of "reflection"? http://docs.oracle.com/javase/tutorial/reflect/ – Jeroen Vannevel Nov 02 '14 at 23:09
  • reflection will do it the nice way. also, you could add all those constants to a static array: private static String[] array = new String[]{STATE_A,STATE_B,STATE_C,STATE_D}; – Michael Nov 02 '14 at 23:11
  • Sadly, no, I have never heard about reflection, but I will check it. I am beginner to Java. Thanks for help:) – bercik Nov 02 '14 at 23:13
  • 1
    IMHO marking the question as a duplicate and downvoting it, is a bit harsh. Especially considering the quality (high) and the experience (low) of the OP. The given link to [Enums VS Classes VS Interfaces](http://stackoverflow.com/questions/6144227) doesn't even provide an answer to the question. – Hille Nov 02 '14 at 23:53
  • Thanks, Hille. To others: quote explicitly where is the answer for my question at that 'duplicate question'. I have seen that 5 times, then asked. I suggest you read again what I look for. – bercik Nov 03 '14 at 12:10

3 Answers3

6

You may write

private static List<String> getListOfAllStates() {
    List<String> list = new ArrayList<String>();

    for (Field field : StateOfSomeProcess.class.getDeclaredFields()) {
        int modifiers = field.getModifiers(); 
        if( Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers) ) {
            list.add(field.getName());
        }
    } 
    return list;
}
Hille
  • 4,096
  • 2
  • 22
  • 32
  • Wow! It works like a charm! I have tested it in a small app. But I am also aware of previous answers and the fact that the reflection should be avoided. I think I can write two other solutions that were pointed out by Jeanne Boyarsky. Thanks Hille! – bercik Nov 16 '14 at 23:47
1

I see three options.

Option 1 - create an ArrayList or array yourself

Pros: Fast and easy to do Cons: Easy to get out of date

Option 2 - Use reflection

Pros: It will always be up to date Cons: Slower to run (highly unlikely to be a problem if you only do it once), harder to read the code

Option 3 - Read the file as a string

Pros: It will also be up to date. Cons: Gives you strings, but not Java references. I sometimes use this approach when writing unit tests (for example to confirm I didn't forget to add something manually using approach #1)

Jeanne Boyarsky
  • 12,156
  • 2
  • 49
  • 59
  • 1
    Although you didn't provide code example solutions, I must admit that I appreciate your answer. It gives some clues to interesting things to check. Maybe I will use one of them temporarily. Upvote for you! – bercik Nov 03 '14 at 11:59
0

It's not exactly what was asked but as I had to get a Map of <Constant, Value> I've modified a bit the Jeanne answer and it may help someone:

public class AnyNamesConstants {
    public static final String CONST_1 = "Constant 1";
    
    public static final String CONST_2 = "Constant 2";
    
    public static Map<String, Object> getMapConstValue() throws IllegalAccessException {
    
        Map<String, Object> map = new HashMap<>();
    
        for (Field field : AnyNamesConstants.class.getDeclaredFields()) {
            int modifiers = field.getModifiers();
            if( Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers) ) {
                list.put(field.getName(), field.get(field.getType()));
            }
        }
        return map;
    }
}

You'd get:

{
    "CONST_1": "Constant 1",
    "CONST_2": "Constant 2"
}
EQuadrado
  • 221
  • 4
  • 4