java 当类被序列化时,为什么 SonarQube 会给出瞬态/私有错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43917902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is SonarQube giving a transient/private error when class is Serialized?
提问by koala421
采纳答案by agabrys
SonarQube marked this line as an error, because java.util.Listdoesn't implement java.io.Serializable. java.util.ArrayListis serializable, but the bondAxeMarkQuoteUpdates
is protected
so somebody can assign other non-serializable list to it (e.g. in a subclass).
SonarQube 将此行标记为错误,因为java.util.List没有实现java.io.Serializable。java.util.ArrayList的是序列化的,但bondAxeMarkQuoteUpdates
就是protected
这样有人可以(在子类中如)指定其他非序列名单吧。
To solve the problem you can:
要解决问题,您可以:
- make the field as
transient
, but it will be ignored during serialization - make the field as
private
, so SonarQube can verify that nobody assigned non-serializable list to it - change the field type to serializable type (e.g. java.util.ArrayList)
- 将该字段设为
transient
,但在序列化过程中将被忽略 - 将该字段设为
private
,以便 SonarQube 可以验证没有人为其分配了不可序列化的列表 - 将字段类型更改为可序列化类型(例如java.util.ArrayList)
回答by Dherik
I receive the same error and the solution was turn the class used on the variable as Serializable
.
我收到相同的错误,解决方案是将变量上使用的类转换为Serializable
.
For example, this show an error because Object
is not Serializable
:
例如,这显示一个错误,因为Object
不是Serializable
:
private Map<String, Object> map = new HashMap<>();
The simplest solution in the case was turn the second parameter Serializable
. So, you could use:
在这种情况下,最简单的解决方案是打开第二个参数Serializable
。所以,你可以使用:
private Map<String, Serializable> map = new HashMap<>();
If you are using your own class (instead of Object
), you can put the class to implements Serializable
.
如果您使用自己的类(而不是Object
),则可以将该类放到implements Serializable
.
回答by benzonico
As stated in the rule documentation (that you can open clicking on the ... in your screenshot) : https://sonarqube.com/coding_rules#rule_key=squid%3AS1948
如规则文档中所述(您可以在屏幕截图中单击 ... 打开):https: //sonarqube.com/coding_rules#rule_key=squid%3AS1948
This rule raises an issue on non-Serializable fields, and on collection fields when they are not private (because they could be assigned non-Serializable values externally)
此规则在非可序列化字段和非私有集合字段上引发问题(因为它们可以从外部分配非可序列化值)