Java反射:避免使用具有默认值的字段 [英] Java Reflection : avoid fields with default values
问题描述
我具有以下类结构:
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屋!