java 如何解决 EI_EXPOSE_REP2 以及为什么它是错误的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10551242/
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
How to solve EI_EXPOSE_REP2 and why exactly its wrong
提问by caarlos0
I ran the FindBugs in my project, and I got the following warning:
我在我的项目中运行 FindBugs,我收到以下警告:
new foo.pkg.Key(Client, Product, Date, String) may expose internal representation by storing an externally mutable object into Key.expireDate MALICIOUS_CODE EI_EXPOSE_REP2 60 Medium
Key
is an Entity which have a Date expireDate
, with its respective getter and setter, and it uses them in the constructor.
Key
是一个实体,它有一个Date expireDate
,带有各自的 getter 和 setter,并在构造函数中使用它们。
So, what's wrong? Why exactly is wrong do this? Is it because Date is a mutable type?
那么,怎么了?为什么这样做是错误的?是因为 Date 是可变类型吗?
Actually, I just return a (Date) dataNascimento.clone()
, and use the same strategy in the setter. Is that the better way of doing this?
实际上,我只是返回 a (Date) dataNascimento.clone()
,并在 setter 中使用相同的策略。这是更好的方法吗?
回答by Peter Schwarz
I would recommend performing your (Date) dataNascimento.clone()
call in the constructor (either directly, or via your setter).
我建议(Date) dataNascimento.clone()
在构造函数中执行您的调用(直接或通过您的 setter)。
Yes, FindBugs is warning you due to the fact that data is mutable. You may have the clone calls in your setters and getters, but you would still get the warning, since you could still might be able alter the the date inside the constructor.
是的,由于数据是可变的,FindBugs 会警告您。您的 setter 和 getter 中可能有克隆调用,但您仍然会收到警告,因为您仍然可以更改构造函数中的日期。