Java反射:避免使用具有默认值的字段 [英] Java Reflection : avoid fields with default values

查看:134
本文介绍了Java反射:避免使用具有默认值的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下类结构:

public Class A{
private int a;
private String b;
private B binst;
}

public Class B{
private int x;
private String y;
}

定义了所有的getter和setter方法.我使用Java反射来调用,如下所示:

All the getters and setters are defined. I use Java reflection to invoke as follows :

method.invoke(ClassAObj, ClassBObj);

现在,在调用此功能之前,我只设置了y而不是x.我将此ClassAObj转换为JSON,发现0的默认值设置为x,它出现在JSON中.我不希望x字段出现在JSON中.我应该如何避免这种情况?

Now, before invoking this, I had only set y and not x. I convert this ClassAObj into JSON and find that the default value of 0 is set for x, and it appears in the JSON. I don't want x field to appear in the JSON. How should I avoid this?

有趣的是,如果我设置了x而不是y,则标记y不会出现在JSON中.

Interestingly, if I set x and not y, the tag y doesn't appear in the JSON.

推荐答案

因为int是一个原语,即:不可为空,通常Json解析器会丢弃空值. 您可以使用reference类型Integer,其默认值为null.

Because int is a primitive, i.e: not nullable, and usually Json parsers discard null values. You can use the reference type Integer and its default will be null .

public Class B{
  private Integer x;
  private String y;
}

这篇关于Java反射:避免使用具有默认值的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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