java - Gson 为什么不将方法都写成静态方法?
怪我咯
怪我咯 2017-04-17 17:40:24
0
5
415

我一直很困惑为啥谷歌不将Gson类中的方法改为静态方法,用起来不是更方便吗?
我的前同事有好多人在结合httpclient使用时都是在发送消息的类中定义了一个属性:
private static Gson gson = new Gson();
调用时,就直接
gson.toJson(obj);
这种使用方法有没有什么潜在问题?
求解答啊...

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(5)
Peter_Zhu

多线程同时调用会有问题吧
以下摘自Gson User Guide:

Sometimes you need to share state across custom
serializers/deserializers (see this discussion). You can use the
following three strategies to accomplish this:
1.Store shared state in static fields
2.Declare the serializer/deserializer as inner classes of a parent type, and use the instance fields of parent type to store shared state
3.Use Java ThreadLocal
1 and 2 are not thread-safe options, but 3 is.

Peter_Zhu

Variable sharing conflicts are prone to occur

迷茫

I would like to ask, is gson written incorrectly as json? Or is there a language called gson?

伊谢尔伦

I think it may be an efficiency problem. Once it is written as static, it will be in the memory as soon as it is loaded, which will undoubtedly reduce the running speed!

PHPzhong

A Gson object may have a custom Adapter inside, see GsonBuilder documentation

If you only need the defaultnew Gson(), you can just use a singleton without any problem

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template