java 可变参数列表,需要在Java可变参数列表中至少有一个元素

博客讨论了如何在Java中确保构造器接收到至少一个参数,从而避免默认无参数构造器被误用。作者提出了一种使用已弃用方法和编译警告作为错误的方法,以在编译时检查参数的存在。此外,还探讨了使用注解来实现类似功能的可能性。
摘要由CSDN通过智能技术生成

In this code construct:

public MyClass(Integer... numbers) {

do_something_with(numbers[]);

}

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.)

Clearly I could do this:

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.

Could there be another way to achieve the same, like some @-annotation that marks this constructor as non-implicit?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值