Reputation: 869
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?
Upvotes: 1
Views: 623
Reputation: 10239
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.
Upvotes: 0
Reputation: 24262
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.
Upvotes: 1
Reputation: 258558
You could use reflection to scan the members of your class and match the names with a pattern like "variable_"
.
Upvotes: 1
Reputation: 500227
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.
Upvotes: 2