22

I am very curious how Jackson creates objects including it's private properties/fields without setters and just using the objects empty constructor.

The reason I'm asking is that when I de-serialize certain properties I want to automatically set other properties based on these values. For example, I would not want to serialize an image but just it's path. Once the path is de-serialized the @JsonIgnore field Image can load the actual image. After the construction of the deserialized object the fields have not yet been assigned. And the getters are logically not being called. So what voodoo magic is touching my objects private parts?

public class ItemTemplate {

    private String imagePath;

    public ItemTemplate() {
        System.out.println(imagePath); //Still null
    }

    public String getImagePath() {
        System.out.println(imagePath); //Not being called when deserializing.
        return imagePath;
    }
}

But when Jackson is done de-serializing this object it has it's imagePath set.

Madmenyo
  • 8,389
  • 7
  • 52
  • 99
  • 6
    Using reflection, after making the private fields accessible. Read http://stackoverflow.com/questions/1555658/is-it-possible-in-java-to-access-private-fields-via-reflection – JB Nizet May 06 '17 at 14:08
  • @JBNizet That's a nice trick. And that made me create a private setter which does the trick for me. Now the path is not exposed and I'm able to set other properties. That indirectly answered my follow up question. Thanks. – Madmenyo May 06 '17 at 14:13

1 Answers1

17

The first comment answered the question in the title. Jackson uses reflection to access private and protected properties. This somehow led me to trying out a private setter for the imagePath field. This setter does get used by Jackson instead of directly accessing the field. Within this setter I could set the actual image using the path string and still remain private.

Community
  • 1
  • 1
Madmenyo
  • 8,389
  • 7
  • 52
  • 99
  • If Jackson can use reflection to access private and protected properties, are getters also unnecessary? – getsadzeg May 10 '22 at 11:47
  • the getters are necessary for YOUR code.. not jackson. – granadaCoder May 11 '22 at 13:34
  • @granadaCoder I am not claiming that Jackson needs private setters. I am answering my own question, how to set additional properties once Jackson has deserialized into an object. Since it uses private setters when deserializing, this is the perfect opportunity to set some other fields that depend on the field with the private setter. – Madmenyo May 18 '22 at 19:58
  • My comments were for the getsadzeg comment. – granadaCoder May 18 '22 at 20:36
  • @granadaCoder I meant if it was unnecessary to Jackson specifically. Whether it's necessary to my code is not relevant in this case. – getsadzeg May 20 '22 at 14:21