lundi 23 novembre 2015

How to check if a field was initialized or contains the default value in Java

I'm mapping a json string to a class using jackson mapper. The class looks like this:

class MyClass{      
    @JsonProperty("my_boolean")
    private boolean myBoolean;

    @JsonProperty("my_int")
    private int myInt;

    //Getters and setters
}

I want to check if the fields myBoolean and myInt were actually set or contain their default values (false and 0). I tried using reflection and checking if the field was null, but I guess that won't work for primitive types. This is what I have now:

Field[] fields = myClass.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {            
                field.setAccessible(true);
                Object myObject = field.get(myClass);
                if(myObject != null) {
                  //Thought this would work, but it doesn't
                }
            }
         }

How else can I check this?

Thanks.





Aucun commentaire:

Enregistrer un commentaire