1

I have a class like this

Class Constants {
    public static final String A = "abc";
    public static final String B = "xyz";
}

I want to get the values of all these String fields and add them to an arrayList

List<String> myStrings = new ArrayList<>();

Field[] fields = Constants.class.getDeclaredFields();

for (Field field : fields) {
    myStrings.add(field.getName());
}

Now field.getName() gives the name of the field, i.e. 'A', but what I want is it's value 'abc'.

Is there a way to do this?

user2653062
  • 697
  • 1
  • 9
  • 16

1 Answers1

2

Try this:

for (Field field : fields) {
    myStrings.add(field.getName());
    myStrings.add((String)field.get(Constants.class));
}
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292