mercredi 16 octobre 2019

How to set properly an object attribute using reflection in Java?

Class to be accessed using reflection

public class Amenities {
    public Integer amenities_id;
    public Integer scenario;
    public String fclass;
    public String location;
    public String buffer;
    public TableInfo[] amenity_info;
}

Using reflection

while (data.next()) {
                Object o = new Amenities();
                Class<?> c = o.getClass();
                for (int i = 0; i < tableUP.length; i++) {
                    try {
                        Field f = c.getDeclaredField(tableUP[i]);
                        f.setAccessible(true);
                        if (!tableUP[i].equals("scenario") || !tableUP[i].equals("amenities_id")) {
                            f.set(o, data.getString(table[i]));
                        } else if (tableUP[i].equals("scenario")) {
                            Integer scen=(Integer)data.getInt(tableUP[i]);
                            f.set(o,scen );                            
                        } else if (tableUP[i].equals("location")) {
                            f.set(o, data.getString(table[i]));
                        } else if (tableUP[i].equals("amenities_id")) {
                        }
                    } catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException | SQLException e) {
                        log.error(e, errorMsg);
                    }
                }
                log.debug(o, "reflection");
                data_in.add((Amenities) o);
                return postStatus;
            }

My code is failing when it sets the value of the integer attribute of the object Amenites using the code Integer scen=(Integer)data.getInt(tableUP[i]); f.set(o,scen );, when I check the results the other values are assigned properly but the value of the field scenario remains in null.

I am sure that the values from the database ResultSet exist, also I tryied setting a static integer value 66, and It only shows the field with a 0value.

Since I am pretty new on Java, I would appreciate you help to find what am I doing wrong?





Aucun commentaire:

Enregistrer un commentaire