需要在Java可变参数列表中至少有一个元素 [英] Requiring at least one element in java variable argument list
问题描述
在此code构造:
public MyClass(Integer... numbers) {
do_something_with(numbers[]);
}
是有可能要求数字
包含以这样的方式至少有一个条目,这是在编译时检查? (在运行时间,当然,我可以检查numbers.length。)
is it possible to require that numbers
contains at least one entry in such a way, that this is checked at compile-time? (At run-time, of course, I can just check numbers.length.)
显然,我可以这样做:
public MyClass(Integer number, Integer... more_numbers) {
do_something_with(number, more_numbers[]);
}
但是这不会是很优雅。
but this isn't going to be very elegant.
我想这样做的原因是为了确保一个子类不完全忘记在所有调用此构造函数,它会默认调用超()
在列表中没有的号码。在这种情况下,我宁愿希望得到熟悉的错误消息:隐式超级构造函数是不确定的。必须明确地调用另一个构造
。
The reason I would like to do this is to make sure that a sub-class does not simply forget to call this constructor at all, which will default to a call to super()
with no numbers in the list. In this case, I would rather like to get the familiar error message: Implicit super constructor is undefined. Must explicitly invoke another constructor
.
难道还有另一种方式来达到同样的,像一些@ -annotation这标志着此构造非隐?
Could there be another way to achieve the same, like some @-annotation that marks this constructor as non-implicit?
推荐答案
我假设一个人难以置信哈克的方式做,这是创建一个无参数方法,并将其标记为pcated德$ P $。然后用这两个标志编译: -Xlint:德precation -Werror
。这将导致任何使用pcated方法去$ P $的是一个编译时错误。
I suppose one incredibly hacky way to do this is to create a no-args method and mark it as deprecated. Then compile with these two flags: -Xlint:deprecation -Werror
. This will cause any use of a deprecated method to be a compile time error.
这篇关于需要在Java可变参数列表中至少有一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!