Java:找出是使用可变参数还是数组调用函数 [英] Java: Find out whether function was called with varargs or array

查看:25
本文介绍了Java:找出是使用可变参数还是数组调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法找出一个接受 varargs 的 Java 函数(或构造函数)实际上是用 varargs 还是用数组调用的?

Is there a way to find out whether a Java function (or a constructor) that takes varargs was actually called with varargs or with an array?

假设我有以下内容:

public class MyCompositeObjects {

    MyObject[] objects;

    MyCompositeObjects(MyObjects... objects) {
        this.objects = Arrays.copyOf(objects,objects.length);
        // or just: this.objects = objects; ?
    }

    // ...
}

可以使用单个 MyObject[] 参数调用构造函数,该参数稍后可能会更改,如果我不在构造函数中复制数组,则这些更改将应用​​于成员变量 对象也是如此,对吧?但是,如果使用多个 MyObject 调用构造函数,则没有其他对数组 * 的引用可以稍后在类之外更改它,因此我可以直接分配它.我能否在构造函数(或者,一般来说,任何接受可变参数的函数)内部说出它是如何被调用的?

The constructor may be called with a single MyObject[] argument, which may change later, and if I do not copy the array in the constructor those changes will apply to the member variable objects as well, right? However, if the constructor is called with several MyObjects, there is no other reference to the array* to change it later outside the class, so I could assign it directly. Can I tell inside the constructor (or, generally, any function that takes varargs) how it was called?

*nb:这个有具体的名称吗?它只是一个匿名数组吗?

*nb: Is there a specific name for this? Is it simply an anonymous array?

推荐答案

不,你不能.这意味着完全透明 - 这段代码:

No, you can't. It's meant to be entirely transparent - this code:

new MyCompositeObjects(a, b);

完全等同于

new MyCompositeObjects(new MyObjects[] { a, b });

如果你可以信任你的调用者做正确的事情,你总是可以创建两个静态方法并将构造函数设为私有:

If you can trust your callers to do the right thing, you could always create two static methods and make the constructor private:

public static MyCompositeObjects createWithCopy(MyObjects[] values) {
    return new MyCompositeObjects(Arrays.copyOf(values, values.length));
}

public static MyCompositeObjects createWithoutCopy(MyObjects... values) {
    return new MyCompositeObjects(values);
}

private MyCompositeObjects(MyObjects[] values) {
    this.objects = values;
}

注意with copy"版本如何不使用可变参数,这应该有助于用户使用正确的版本.

Note how the "with copy" version doesn't use varargs, which should help users to use the right version.

这篇关于Java:找出是使用可变参数还是数组调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆