dimanche 5 juillet 2020

Accessing a value of a string defined in a interface of constants

I have a constant interface file like so ->

public interface MyConstants {
    String CONSTANT_ONE = "foo";
    String CONSTANT_TWO = "hello";
}

How do I iterate over this to get the values of the constant? I saw a method using reflect where you can access it like this ->

Field[] interfaceFields = MyConstants.class.getFields();
for(Field f : interfaceFields) {
   f.get(f.getName());
}

This returns an object but I want it to be of type String. I know I can typecast it but what's the correct way of doing this?





Aucun commentaire:

Enregistrer un commentaire