0

Gson can deserialize an object like

GsonBuilder gsonBuilder = new GsonBuilder();
    Myclass act = gsonBuilder.create().fromJson(someJson, this.getClass());

Here we pass the Class of the model. The question is how does Gson create an object from the Class? Are they using ClassLoader? If yes, can you help me with it? Or can we create a custom Object with tokens from the json at runtime and cast it to the required class? This question also hints at this. Can a Java class add a method to itself at runtime?

Community
  • 1
  • 1
Debanjan
  • 2,817
  • 2
  • 24
  • 43
  • Basically by assuming that the `Class` follows [bean conventions](https://en.wikipedia.org/wiki/JavaBeans): create a new object with a non-arg constructor and set members by [reflection](https://docs.oracle.com/javase/tutorial/reflect/member/index.html). – PeterMmm Nov 02 '16 at 08:00
  • @PeterMmm How can I create new object from the Class? Can you provide some code or reference to such? That would be very helpful. – Debanjan Nov 02 '16 at 08:35
  • like [this.getClass().newInstance();](https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#newInstance()). – PeterMmm Nov 02 '16 at 11:10

0 Answers0