jeudi 2 janvier 2020

Java Reflection does not Loop to Check for Attributes

I was having some problem when trying to loop to set the field values by using Reflection library in Java. What I am trying to do is whenever the field value is -9999 or "Z", I then modify it to 0 or "". Here is my code:

public static void initializeObject(vtModule.acct obj){
     ReflectionUtils.doWithFields(obj.getClass(), field -> {
         log.debug("Field name: " + field.getName());
         log.debug("Field value: "+ field.get(obj));
             if (field.get(obj).equals(-9999)) {
                 log.debug("COME IN -9999");
                 field.setAccessible(true);
                 field.setInt(obj, 0);
             }

             if (field.get(obj).equals("Z")) {
                 log.debug("COME IN Z");
                 field.setAccessible(true);
                 field.set(obj, "");
             }
     });
}

My class object as such:

public final class acct {
public String date_inactive;
public String purchase_order;
public int child_count;
public char vip_code;
public short testInt;
public int testInt2;
}

The part where the code initialize the object with default values which I am not supposed to change, that is the reason why I have to come out with another function to convert the -9999 value to 0 and "Z" value to "":

static vtModule.acct initAcct(vtModule.acct account) {
    account.date_inactive="";
    account.purchase_order="";
    account.child_count=-9999;
    account.vip_code='Z';
    account.testInt=-9999;
    account.testInt2=-9999;
}

From the console printed out, some of the fields with -9999 values are set to 0, namely child_count and testInt2. I not sure why sometimes when the field value is -9999, it does not go into the if statement to reset the value. Same goes for field with "Z" value.

Any ideas? Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire