我一直很困惑为啥谷歌不将Gson类中的方法改为静态方法,用起来不是更方便吗?
我的前同事有好多人在结合httpclient使用时都是在发送消息的类中定义了一个属性:
private static Gson gson = new Gson();
调用时,就直接
gson.toJson(obj);
这种使用方法有没有什么潜在问题?
求解答啊...
一个Gson object内部可能有自定义Adapter,见GsonBuilder文档
如果你只需要默认的new Gson()
, 可以只用一个singleton没有问题
弱弱的问一下,gson 是 json 写错了 还是有一种叫 gson 的语言?
我觉得可能是效率的问题,一旦写为 static ,则一加载就在内存中了,而这无疑会降低运行速度!
多线程同时调用会有问题吧
以下摘自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.
容易出现变量共享冲突