方法中的java可选参数 [英] java optional parameter in methods
问题描述
我想制作一个带有1个必需参数和1个可选参数的方法,但是我发现了如何通过在参数(int ... b)中创建一个可选数组的方法,但这是针对数组的,我想要使它成为此值是null还是用户输入它,我可以通过使用相同名称的2个方法(其中一个使用单个参数,而一个使用2个参数)来实现,但是可以仅使用一种方法来完成?
I want to make a method that takes 1 required parameter and 1 optional parameter, but I found how to make an optional array which is by making in the parameter (int... b) but this is for an array, I want to make it just either this value is null or the user entered it, I can make it by making 2 methods of the same name but one with the single parameter and one with the 2 parameters, but can it be done with just one method?
谢谢
推荐答案
否,Java不支持可选参数.重载的另一种替代方法(对两个参数没有多大意义,但确实对更多参数有意义)是使用表示所有参数的构建器类型-您可以为构建器提供一个构造器,包含必需的参数,然后是每个可选参数的设置器,使设置器返回生成器本身.因此,调用该方法将类似于:
No, Java doesn't support optional parameters. Another alternative to overloading (which doesn't make much sense for two parameters but does make sense for more) is to use a builder type which represents all the parameters - you can provide a constructor for the builder which contains the required parameters, and then a setter for each of the optional ones, making the setter return the builder itself. So calling the method becomes something like:
foo.doSomething(new ParameterBuilder(10).setBar(2).setBaz(10));
这篇关于方法中的java可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!