Java 代码 - 为什么要在此处克隆变量?

发布于 2024-10-01 14:58:36 字数 361 浏览 0 评论 0原文

看一下我从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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你如我软肋 2024-10-08 14:58:37

因为它可以从这个方法的外部改变?

Because it could be changed from the outside of this method?

走野 2024-10-08 14:58:36

此代码保护自身免受外部调用者更改 HashTable 状态的影响。

通过对其进行克隆,它们可以确保对传入的哈希表所做的更改不会反映在表传入的方法/对象内部。

使用数组的一个简短示例:

//Outside code
int[] arr = new int[]{0, 1, 2, 3};

// method of class
public void init(int[] arr) {
    this.arr = arr; 
}

//meanwhile, in the external code
arr[0] = 42; // this change to the array will be reflected inside the object.

可以通过复制数组来避免该漏洞。对原始数组的更改不会显示在副本中。

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 the Hashtable that was passed in are not reflected inside of the method/object the table was passed into.

A short example using arrays:

//Outside code
int[] arr = new int[]{0, 1, 2, 3};

// method of class
public void init(int[] arr) {
    this.arr = arr; 
}

//meanwhile, in the external code
arr[0] = 42; // this change to the array will be reflected inside the object.

That vulnerability can be avoided by making a copy of the array. Changes to the original array will not show up in the copy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文