3

Is there a way to avoid reflection in Gson? I know that when you will use registerTypeAdapter you can avoid it, but if you use @SerializedName("name") annotation on class member, can you avoid id too?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Szymon Haxik
  • 121
  • 1
  • 8
  • 1
    Everything serializers do involves reflection. To use the `TypeAdapter` Gson has to determine the type of your object. Can you clarify why you need this, what you're trying to achieve? – Sotirios Delimanolis May 12 '16 at 21:32
  • And aren't runtime annotations determined using reflection? – Christopher Schneider May 12 '16 at 21:35
  • 1
    I think Soltirios wants a way to exclude a field inspection through reflexion (performance or to avoid infinite cycles). If that's the case check documentation or this link: http://stackoverflow.com/questions/4802887/gson-how-to-exclude-specific-fields-from-serialization-without-annotations – corlaez May 12 '16 at 21:39
  • @SotiriosDelimanolis Reflection is very slow on android, this is why I want to avoid it ;). I saw an article, where authors wrote, that using TypeAdapter and custom deserializers we can avoid reflection. But I'm just curious that there is another way to achieve that – Szymon Haxik May 12 '16 at 21:44
  • @ChristopherSchneider it depends on annotation implementation. Some of anntotations use reflection, but some of them use code injection. – Szymon Haxik May 12 '16 at 21:45
  • 1
    Yes reflection is slow, but you should be doing this work on a background thread so it typically not that big of a deal. – cyroxis May 12 '16 at 21:53
  • @cyroxis there is no way to do it on main thread, because I'm doing network calls. On android reflection is a lot slower than on pure java, there are a lot of articles about that. My question was simple - Do `@SerializedName` uses reflection or not? – Szymon Haxik May 12 '16 at 22:17
  • 1
    Yes it uses reflection. Yes reflection is slower on Android. I am using Gson in an Android project and deserializing 10k+ entities from single network calls. It is typically not a big issues if you don't block the main thread. – cyroxis May 12 '16 at 22:24

1 Answers1

1

You can use Autovalue and Autovalue-gson that will create a reflection free adapter for you.

mbonnin
  • 6,893
  • 3
  • 39
  • 55