lundi 26 mars 2018

How to reflectively assign enum fields given String representations of their constants (Java)

Let's say I have the enum of week days (it doesn't have to be week days, but for simplicity's sake)

public enum WeekDay {
    // all of the different days of the week in capitals
    MONDAY, TUESDAY, // ...
}

And then I have a class foo which holds two references to the WeekDay constants, one of which holds a null value:

public class Foo {
    private WeekDay day = MONDAY;
    private WeekDay day2 = null; 

    // other unimportant information
    private int i = 4; 
    private String blah = "blah";
}

If I have an array of the fields such that:

Field[] fields = Foo.getClass().getDeclaredFields(); // something like that

And wish to edit all enum fields:

for(Field f : fields) {
    if(f.isEnumConstant()) {
        // field must be holding an enum...
    }
}

Now I have a String that holds teh value "TUESDAY" which is a known constant within the weekdays enum.

String input = "TUESDAY";

So I wish to use

Enum.valueOf(... , input);

to reflectively input the value of the enum with the given input string "TUESDAY", through something along the lines of:

String input = "TUESDAY";
Foo foo = new Foo();

for(Field f : fields) {
    if(f.isEnumConstant()) {
        try {
            f.set(Enum.valueOf(... f.getType(), input), foo); // where getType would return the enum class
        }
    }
}

so that, theoretically both day, and day2 should hold the constant of TUESDAY

but f.getType() returns an instance of the Class type, and so Enum.valueOf(); does not accept it as a parameter because java.lang.Enum (which it requires) directly extends java.lang.Object and not Class. Therefore, how could I set the enum value of both day and day2 in this situation to the TUESDAY constant given the String value of "TUESDAY". (if it is possible of course)

The reason I ask is because I am writing an orm io wrapper which takes input from an .xls input file as string representations of the field values and attempts map them to fields using reflection. As such, I'm trying to keep things extremely abstract, and thus direct references to the WeekDay.class cannot be made, and since day2 holds null, I cannot cast the field's values as an enum, and then use:

Enum.valueOf((Enum)f.get(blah), input);





Aucun commentaire:

Enregistrer un commentaire