3

Specifically I am wondering how when deserializing an object the deserializer could set a private field? Thinking of an example class like this:

public class MyClass {
    @JsonProperty( "My String" );
    private String myString;
}

If this is deserialized using objectMapper.readValue(json, MyClass.class); how does the resulting object have this field set if it is marked as private?

Ben
  • 1,638
  • 2
  • 14
  • 21
  • 1
    Related: [What is reflection and why is it useful?](https://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful). – Slaw Aug 14 '20 at 23:27

3 Answers3

4

The short answer is that it can't normally. We use lombok to generate the getter/setter for the variables, but you can of course write your own. Jackson has the same visibility as your main code does, so a private field cannot be mapped without some public getter/setter OR configuring the object mapper like so... objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);.

It wouldn't be able to serialize that either normally. You can use Lombok @Getter and @Setter on the class level so Jackson can work with myString, or put @JsonAutoDetect(fieldVisibility = Visibility.ANY) at the class level like below.

@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class MyClass {
    @JsonProperty( "My String" );
    private String myString;
}
Barton Durbin
  • 335
  • 1
  • 10
3

Calling Field.setAccessible(true) before reading or writing a value through reflection does the trick here.

For details see the corresponding javadoc: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible-boolean-

But use with care ;-)

rmunge
  • 3,653
  • 5
  • 19
2

Quite a few frameworks allow access to private fields in this manner by using Field.setAccessible(true). It allows the application to ignore the Java language visibility rules (i.e. private) and read or change the value via an instance of the Reflection API Field class.

A little more can be found in this question: Java reflection - impact of setAccessible(true)

drekbour
  • 2,895
  • 18
  • 28