Does GSON access private members of a class directly without invoking its getter methods to fetch the value ?
The rule of Java that is followed is if class B has a private member it cannot be accessed by class A without getter/setter methods.
Now I was working on a project with GSON where in I get a feel getter/setter methods are being bypassed [not used,and private member is directly accessed]
I'm just a student so I could possibly be missing some common working.
Class A:
public class A {
public static void main(String[] args) {
B b = new B();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(b));
System.out.println("--end--");
}
}
Class B:
public class B {
private int a;
public B() {
a = 1;
}
public int getA() {
System.out.println("I am invoked!");
return 10;
}
public void setA(int a) {
this.a = a;
}
}
Note : B.a
is assigned value of 1
, and I coded getA()
to always return 10
If I access B.a
from class A
, EVERYTHING WORKS AS EXPECTED and it wont let me do it , all fine till here
GSON doubt starts here
public class A {
public static void main(String[] args) {
B b = new B();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(b));
System.out.println("--end--");
}
}
Since B.a
is private it is supposed to invoke the getter method that is coded to always return 10 BUT the output I get is
Output:
{
"a": 1
}
--end--
so in other words my getter method for the private method is NEVER INVOKED