(给
ImportNew加星标,提高Java技能)
线上事故回顾
前段时间新增一个特别简单的功能,晚上上线前 Review 代码时想到公司拼搏进取的价值观临时加一行 log 日志,觉得就一行简单的日志基本上没啥问题,结果刚上完线后一堆报警,赶紧回滚了代码,找到问题删除了添加日志的代码,重新上线完毕。
情景还原
定义了一个 CountryDTO:
public class CountryDTO {
private String country;
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return this.country;
}
public Boolean isChinaName() {
return this.country.equals("中国");
}
}
定义测试类 FastJonTest:
public class FastJonTest {
@Test
public void testSerialize() {
CountryDTO countryDTO = new CountryDTO();
String str = JSON.toJSONString(countryDTO);
System.out.println(str);
}
}
运行时报空指针错误:
![](http://mmbiz.qpic.cn/mmbiz_jpg/PocakShgoGEPcfuvpE46u0rMfPDoPrBzhgEy3e65nZQSU52dhq4cNsXmvKfsFib7qKQz9Bp9ZqeMGib1uNxwIawg/640?wx_fmt=jpeg&from=appmsg)
通过报错信息可以看出来是 序列化的过程中执行了 isChinaName() 方法,这时候 this.country 变量为空, 那么问题来了:
- 序列化为什么会执行 isChinaName()呢 ?
源码分析
通过 debug 观察调用链路的堆栈信息。
![](http://mmbiz.qpic.cn/mmbiz_jpg/PocakShgoGEPcfuvpE46u0rMfPDoPrBzxvdRpibINSX8RIxIHtibFGGac55vWyqj4oIwiaPjnDs7OCCiaEdDFBZNIA/640?wx_fmt=jpeg&from=appmsg)
![](http://mmbiz.qpic.cn/mmbiz_jpg/PocakShgoGEPcfuvpE46u0rMfPDoPrBzJZKXWLAJMjfiayTERaWtxwDWBkhBIYhD1Zs07bpJyMB9JwemjyvEqOQ/640?wx_fmt=jpeg&from=appmsg)
调用链中的 ASMSerializer_1_CountryDTO.write 是 FastJson 使用 ASM 字节码框架动态生成了一个类 ASMSerializer_1_CountryDTO。
ASM 技术其中一项使用场景就是通过到动态生成类用来代替 Java 反射,从而避免重复执行时的反射开销。
JavaBeanSerizlier 序列化原理
通过下图看出序列化的过程中,主要是调用 JavaBeanSerializer 类的 write() 方法。
![](http://mmbiz.qpic.cn/mmbiz_jpg/PocakShgoGEPcfuvpE46u0rMfPDoPrBzTruKdOmSJ7YHxicDtY6DEAy0xAMUFX7hqk4oeIewmPR0HMTicFsO0KUw/640?wx_fmt=jpeg&from=appmsg)
而 JavaBeanSerializer 主要是通过 getObjectWriter() 方法获取,通过对 getObjectWriter() 执行过程的调试,找到比较关键的 com.alibaba.fastjson.serializer.SerializeConfig#createJavaBeanSerializer 方法,进而找到 com.alibaba.fastjson.util.TypeUtils#computeGetters。
public static List computeGetters(Class> clazz, JSONType jsonType, Map aliasMap, Map fieldCacheMap, boolean sorted, PropertyNamingStrategy propertyNamingStrategy){
Method[] methods = clazz.getMethods();
for(Method method : methods){
if(method.getReturnType().equals(Void.TYPE)){
continue;
}
if(method.getParameterTypes().length != 0){
continue;
}
JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class);
if(annotation != null){
if(!annotation.serialize()){
continue;
}
if(annotation.name().length() != 0){
}
}
if(methodName.startsWith("get")){
}
if(methodName.startsWith("is")){
}
}
}
从代码中大致分为三种情况:
- @JSONField(.serialize = false, name = "xxx") 注解
序列化流程图
![](http://mmbiz.qpic.cn/mmbiz_jpg/PocakShgoGEPcfuvpE46u0rMfPDoPrBzOxm2r2TMVozB7Q3we6ZbJCFC5US7ibr7ibiaI8h6x6Uy8Il7HtO3k4FuA/640?wx_fmt=jpeg&from=appmsg)
示例代码
@JSONType(ignores = "otherName")
public class CountryDTO {
private String country;
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return this.country;
}
public static void queryCountryList() {
System.out.println("queryCountryList()执行!!");
}
public Boolean isChinaName() {
System.out.println("isChinaName()执行!!");
return true;
}
public String getEnglishName() {
System.out.println("getEnglishName()执行!!");
return "lucy";
}
public String getOtherName() {
System.out.println("getOtherName()执行!!");
return "lucy";
}
@JSONField(serialize = false)
public String getEnglishName2() {
System.out.println("getEnglishName2()执行!!");
return "lucy";
}
public void getEnglishName3() {
System.out.println("getEnglishName3()执行!!");
}
public String isChinaName2() {
System.out.println("isChinaName2()执行!!");
return "isChinaName2";
}
}
运行结果为:
isChinaName()执行!!
getEnglishName()执行!!
{"chinaName":true,"englishName":"lucy"}
代码规范
可以看出来序列化的规则还是很多的,比如有时需要关注返回值,有时需要关注参数个数,有时需要关注 @JSONType 注解,有时需要关注 @JSONField 注解;当一个事物的判别方式有多种的时候,由于团队人员掌握知识点的程度不一样,这个方差很容易导致代码问题,所以尽量有一种推荐方案。
这里推荐使用 @JSONField(serialize = false) 来显式的标注方法不参与序列化,下面是使用推荐方案后的代码,是不是一眼就能看出来哪些方法不需要参与序列化了。
public class CountryDTO {
private String country;
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return this.country;
}
@JSONField(serialize = false)
public static void queryCountryList() {
System.out.println("queryCountryList()执行!!");
}
public Boolean isChinaName() {
System.out.println("isChinaName()执行!!");
return true;
}
public String getEnglishName() {
System.out.println("getEnglishName()执行!!");
return "lucy";
}
@JSONField(serialize = false)
public String getOtherName() {
System.out.println("getOtherName()执行!!");
return