1

I have this class in Java in which I declared a large number of variables (more than 50) as:

    public static final String variable_1 = "value";
    ....

I would like to access all these variables and put them in a list from within another class. Is there any way of doing that by using a for loop?

3
  • 2
    Storing them in an array sounds useless to me. Commented Oct 31, 2011 at 13:20
  • 2
    It smells of a Daily WTF here:P Commented Oct 31, 2011 at 13:20
  • static final fields can be inlined by the compiler. This means you can change them using reflection but the code which used the constants no longer refers to them to runtime. Commented Oct 31, 2011 at 13:27

4 Answers 4

2

The only way your can do this without referencing each variable explicitly, is through reflection.

Having said that, a better way would be to refactor your code so that you don't have to do this.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use reflection to scan the members of your class and match the names with a pattern like "variable_".

Comments

1

If you have 50 of them, and they are related constants, they should be represented by an enum (or several enums depending on the constants). This would then provide a natural grouping and access to a list via the values() method.

What you are currently attempting sounds like a code smell.

Comments

0

You can use reflection API, like this:

for (Field f : MyClass.class.getDeclaredFields()) {
    if (f.getName().startsWith("variable_")) {
        System.out.println("Field " + f.getName() + " with value " + f.get(null));
    }
}

As others said, though, this is pretty ugly and probably indicates some bad design decisions.

1 Comment

not my design...i got it like this..i am suppossed to expand it...but not change the existing code

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.