Download Android App in your Android Device from Google Play Store
- Search for "Withoutbook Practice Exam Test" in Mobile/Tablet Play Store
Prepare Interview

Exams Attended

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Google Gson Interview Questions and Answers

Ques. What is Instance Creator? Why and when do we require this?
In most of the cases, Gson library is smart enough to create instances even if any class does not provide default no-args constructor. But, if you found any problem using a class having no no-args constructor, you can use InstanceCreator support. You need to register the InstanceCreator of a java class type with Gson first before using it.

For example, does not have any default constructor.
public class Department
   public Department(String deptName)
      this.deptName = deptName;
   private String deptName;
   public String getDeptName()
      return deptName;
   public void setDeptName(String deptName)
      this.deptName = deptName;
   public String toString()
      return "Department [deptName="+deptName+"]";

And our Employee class has reference of Department as:
public class Employee
   private Integer id;
   private String firstName;
   private String lastName;
   private List<String> roles;
   private Department department; //Department reference
   //Other setters and getters

To use Department class correctly, you need to register an InstanceCreator for as below:
class DepartmentInstanceCreator implements InstanceCreator<Department> {
   public Department createInstance(Type type)
      return new Department("None");
//Now <strong>use the above InstanceCreator</strong> as below
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Department.class, new DepartmentInstanceCreator());
Gson gson = gsonBuilder.create();
Employee [id=1, firstName=Arindam, lastName=Ghosh, roles=[FINANCE, MANAGER], department=Department [deptName=Finance]]
Is it helpful? Yes No

Most helpful rated by users:

©2020 WithoutBook