[英]Java Reflection : avoid fields with default values
I have the following class structure: 我具有以下类结构:
public Class A{
private int a;
private String b;
private B binst;
}
public Class B{
private int x;
private String y;
}
All the getters and setters are defined. 定义了所有的获取器和设置器。 I use Java reflection to invoke as follows :
我使用Java反射来调用,如下所示:
method.invoke(ClassAObj, ClassBObj);
Now, before invoking this, I had only set y
and not x
. 现在,在调用此
x
之前,我只设置了y
,没有设置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. 我该转换成ClassAObj JSON和发现的默认值
0
设置为x
,它出现在JSON。 I don't want x
field to appear in the JSON. 我不希望
x
字段出现在JSON中。 How should I avoid this? 我应该如何避免这种情况?
Interestingly, if I set x
and not y
, the tag y
doesn't appear in the JSON. 有趣的是,如果我设置
x
而不是y
,则标记y
不会出现在JSON中。
Because int
is a primitive, ie: not nullable, and usually Json
parsers discard null values. 因为
int
是一个原始值,即:不能为空,通常Json
解析器会丢弃空值。 You can use the reference
type Integer
and its default will be null
. 您可以使用
reference
类型Integer
并且其默认值将为null
。
public Class B{
private Integer x;
private String y;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.