Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting all static variables in a class into array/list

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

like image 617
Chandra Avatar asked Dec 17 '10 00:12

Chandra


People also ask

What does static {} do in Java?

In the Java programming language, the keyword static means that the particular member belongs to a type itself, rather than to an instance of that type. This means we'll create only one instance of that static member that is shared across all instances of the class.

Are static variables shared by all objects of a class?

Class Variables and MethodsA static variable is shared by all instances of a class. Only one variable created for the class.

Can a list be static?

Static lists: these lists do not update as new records meet or existing records no longer meet the criteria. They are a snapshot of records that meet a certain set of requirements when the list was created and saved.

Can static variables be declared outside the class?

We declare a static variable in a class and initialize the variable outside the class, but we use the variable within the function. There's a general distinction in C++ between declaration and definition. It's possible to do both at once in some cases but this isn't one of them.


1 Answers

You could use reflection:

Field[] fields = DummyClass.class.getDeclaredFields();
for (Field f : fields) {
    if (Modifier.isStatic(f.getModifiers()) && isRightName(f.getName())) {
        doWhatever(f);
    } 
}
like image 186
Cameron Skinner Avatar answered Sep 28 '22 05:09

Cameron Skinner