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 DummyC开发者_运维百科lass 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
You could use reflection:
Field[] fields = DummyClass.class.getDeclaredFields();
for (Field f : fields) {
if (Modifier.isStatic(f.getModifiers()) && isRightName(f.getName())) {
doWhatever(f);
}
}
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());
精彩评论