简体   繁体   English

方法重载null参数

[英]Method Overloading null parameter

In my code, I have a method which has got to take 4 parameters. 在我的代码中,我有一个必须采用4个参数的方法。 But in somewhere in the code i call this method with sometimes 2, sometimes 4 parameters. 但是在代码的某处,我有时用2个参数,有时用4个参数来调用此方法。 So when i call with 2 parameters, the last 2 parameters should go automaticly null. 因此,当我使用2个参数调用时,最后2个参数应自动​​为空。

For example: 例如:

public static void x(String one,String two,String three=null,String four=null){

//do something hear

}

x("one","two");
x("one","two","three","four");

When I call x("one","two") => I want that the three and four parameters automatticaly initialize to null. 当我调用x(“ one”,“ two”)=>时,我希望三个和四个参数automatticaly初始化为null。

How can i do that ? 我怎样才能做到这一点 ? Thanks for helps. 感谢您的帮助。

class A{

   public void do(String a, String b, String c, String d){
        //do something
   }

   //Overload do method
   public void do(String a, String b){
        do(a,b,null,null);
   }
}

Best option is to keep your method with 4 parameters only, just when you need to pass only 2 parameters, pass the other 2 parameters as null. 最好的选择是让您的方法仅包含4个参数,仅当您只需要传递2个参数时,将其他2个参数传递为null。

For Example for 2 params pass: 例如2个参数传递:

    x(a,b,null,null);

and for 4 params pass: 并通过4个参数:

    x(a,b,c,d);

This works as well and can be called using an Array of Strings as parameter, or multiple comma separated Strings. 这也可以正常工作,并且可以使用字符串数组作为参数或多个逗号分隔的字符串来调用。 This way you don't have to overload. 这样,您不必超载。

public void myMethod(String ...strings)  {
    for (String string : strings) {
        //do something with the string
    }
}

you can call it using an array: 您可以使用数组来调用它:

myMethod(new String[]{"test1", "test2"})

or several Strings: 或几个字符串:

myMethod("test1", "test2");
myMethod("test1", "test2", "test3", "test4");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM