问题描述
以下是我的情景:
我必须调用方法。让参数为:
参数1,参数2,..,..,参数N
但是发送给方法的参数可能会在每种情况下都发生变化。
I've got to call a method. Let the parameters be:Parameter1, Parameter2, .. , .. , Parameter NBut the Parameters to be sent to the method might change in each case.
案例1:仅发送参数1
案例2:发送参数组合
案例3:所有参数都已发送
什么是最好的方法在Java中实现这一点?
What is the best way to achieve this in Java ?
推荐答案
解决方案取决于问题的答案 - 所有参数都是相同的类型如果是这样,每个都会被处理相同吗?
The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?
如果参数不是同一类型或更重要的是不会被视为相同,那么你应该使用方法重载:
If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:
public class MyClass
{
public void doSomething(int i)
{
...
}
public void doSomething(int i, String s)
{
...
}
public void doSomething(int i, String s, boolean b)
{
...
}
}
但是,如果每个参数都是相同的类型并且将以相同的方式处理,那么您可以在Java中使用变量args功能:
If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:
public MyClass
{
public void doSomething(int... integers)
{
for (int i : integers)
{
...
}
}
}
显然,当使用变量args时,你可以通过索引访问每个arg,但我建议不要这样做,因为在大多数情况下它会暗示你的设计中存在问题。同样,如果您在迭代参数时发现自己正在进行类型检查,那么您的设计需要进行审核。
Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.
这篇关于Java:向方法发送多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!