为什么varargs应该是方法签名中的最后一个? [英] Why varargs should be the last in method signature?

查看:76
本文介绍了为什么varargs应该是方法签名中的最后一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试编写如下方法

If I try to write a method like below

public void someStuff(Object ... args, String a )

我收到此错误


someStuff方法的变量参数类型Object必须是最后一个参数。

The variable argument type Object of the method someStuff must be the last parameter.

我不完全理解这个要求变量参数类型是最后一个。
任何输入都会有所帮助。

I don't fully understand the requirement of variable argument type to be the last. Any inputs will be helpful.

推荐答案

它遵循C约定。反过来,C约定基于CPU架构,它在堆栈上传递参数。第一个非vararg参数以堆栈帧中的固定偏移量结束。如果您可以先放置vararg参数,则以下参数的堆栈偏移量将取决于您将传递多少个vararg参数。这将极大地复杂化访问它们所需的代码量。

It follows the C convention. The C convention in turn is based on CPU architectures which pass arguments on the stack. The first non-vararg arguments end up at a fixed offset in the stackframe. If you could put the vararg arguments first, the stack offset of the following arguments would depend on how many vararg parameters you would have passed. This would greatly complicate the amount of code needed to access them.

在您的示例中,首先使用 String a ,它在概念上在偏移0处独立于后面的vararg参数的数量。但是最后使用 String a ,它可能在偏移0,4,8,12等处 - 你必须计算 args.size * 4 每次需要时字符串a

In your example, with String a first, it's conceptually at offset 0 independent how the number of vararg arguments that follow. But with String a last, it could be at offset 0, 4, 8, 12 etc - you'd have to calculate args.size * 4 everytime you needed String a.

这篇关于为什么varargs应该是方法签名中的最后一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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