Java 代码 - 为什么要在此处克隆变量?
看一下我从javax.naming.InitialContext复制的以下代码。 HashTable 类型的参数被传递给构造函数。这是代码片段
public InitialContext(Hashtable<?,?> environment) throws NamingException
{
if (environment != null) {
environment = (Hashtable)environment.clone();
}
init(environment);
}
我的问题是,为什么环境可以直接传递给 init 方法而在这里被克隆?
Look at the following code which i am copying from javax.naming.InitialContext. An argument of HashTable type is being passed to the constructor. here is the code snippet
public InitialContext(Hashtable<?,?> environment) throws NamingException
{
if (environment != null) {
environment = (Hashtable)environment.clone();
}
init(environment);
}
My question is, why environment is being cloned here when it could have been passed directly to init method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为它可以从这个方法的外部改变?
Because it could be changed from the outside of this method?
此代码保护自身免受外部调用者更改
HashTable
状态的影响。通过对其进行克隆,它们可以确保对传入的哈希表所做的更改不会反映在表传入的方法/对象内部。
使用数组的一个简短示例:
可以通过复制数组来避免该漏洞。对原始数组的更改不会显示在副本中。
This code is protecting itself from an external caller changing the state of the
HashTable
.By making a
clone
of it, they ensure that changes made to theHashtable
that was passed in are not reflected inside of the method/object the table was passed into.A short example using arrays:
That vulnerability can be avoided by making a copy of the array. Changes to the original array will not show up in the copy.