0

In my code, I have a method which has got to take 4 parameters. But in somewhere in the code i call this method with sometimes 2, sometimes 4 parameters. So when i call with 2 parameters, the last 2 parameters should go automaticly null.

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.

How can i do that ? Thanks for helps.

4

3 回答 3

3
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);
   }
}
于 2013-10-08T08:21:24.843 回答
0

这也很有效,可以使用字符串数组作为参数或多个逗号分隔的字符串来调用。这样你就不必超载了。

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

您可以使用数组调用它:

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

或几个字符串:

myMethod("test1", "test2");
myMethod("test1", "test2", "test3", "test4");
于 2013-10-08T09:45:42.360 回答
0

最好的选择是让你的方法只使用 4 个参数,当你只需要传递 2 个参数时,将其他 2 个参数传递为 null。

例如 2 个参数传递:

    x(a,b,null,null);

对于 4 个参数传递:

    x(a,b,c,d);
于 2013-10-08T08:23:57.340 回答