Java: Find out whether function was called with varargs or array

后端 未结 2 1930
梦如初夏
梦如初夏 2021-01-12 13:58

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?

Say I have the following:

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-12 14:46

    The only way to know is to parse the code. This is because varargs is basicaly a compile time feature and doesn't change how the program runs.

    If in doubt, I would always copy the array. Unless you know this will be a performance issue.

    BTW: You can do the following.

    MyCompositeObjects(MyObjects o1, MyObjects... objects) {
    
    MyCompositeObjects(MyObjects[] objects) {
    

    However, this likely to do the opposite of what you want.

    Another option is to use a static factory.

    private MyCompositeObjects(MyObjects[] objects) {
       this.objects = objects;
    }
    
    MyCompositeObjects create(MyObjects... objects) {
        return new MyCompositeObjects(objects.close());
    }
    
    MyCompositeObjects createNotCopied(MyObjects... objects) {
        return new MyCompositeObjects(objects, false);
    }
    

    Use the more cumbersome method name for the less safe version. This means if a method is chosen without much thought, the safe version is more likely to be used.

提交回复
热议问题