简体   繁体   中英

GSON directly accesses private members?

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 : Ba is assigned value of 1 , and I coded getA() to always return 10

If I access Ba 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 Ba 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

What you're talking about is encapsulation. This is an Object Orientated concept that restricts the access of certain class members.

However, Java has another way of accessing the values in an object. That is, reflection. This allows for a more generic access to a class. For example, in the case of Gson, they need to know about each field in a class, but they can't write a method for every class in existence. Likewise, they can't ask you to write a JSON adapter for it. That defeats the point of the framework.

In comes Reflection. It allows the Gson library to have a single method that converts any object into some JSON. This is important because the Reflections library provides an API for getting at private members of a class without going through the accessors and mutators.

Extra Reading

  • You should have a look into Reflection . It is a very powerful API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM