java - Gson 为什么不将方法都写成静态方法?

查看:426
本文介绍了java - Gson 为什么不将方法都写成静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

解决方案

多线程同时调用会有问题吧
以下摘自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.

这篇关于java - Gson 为什么不将方法都写成静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆