mercredi 7 octobre 2020

How to get and initialize field through reflection?

I have a class ColorConstants with some static fields:

public class ColorConstants {
    public static final Color BLACK;
    public static final Color BLUE;
    public static final Color GREEN;
    public static final Color RED;
    // ....
}

I want to check if a given color (String) exists in that class.

Is using reflections the appropriate way?

String s = "RED";
Field f = ColorConstants.class.getField(s);
Color colorConstant = (Color) myField.get(null);

Here I'm not sure how to get the actual value.
So what I basically need is: either ColorConstant.RED (if exists) or null (if doesn't exist).

PS: ColorConstants is not my own class, I just work with it. So I can't change its structure to an enum.





Aucun commentaire:

Enregistrer un commentaire