Мне нравится делать это немного по-другому, что, на мой взгляд, обеспечивает большую гибкость. Это может устранить необходимость в различных перегрузках. Приведенный ниже пример метода устраняет необходимость во всех методах, содержащихся в вашем тестовом классе, и обеспечивает большую гибкость, например:
Он может дополнительно принимать NONE для неограниченного числа строковых аргументов:
new Test().method();
or
new Test().method("This is a String.");
or
new Test().method("This ", "is", " a", " string", " that", " will ", "be", " displayed.");
Он также может принимать одномерный (1D) строковый массив в качестве одного аргумента.
String[] stringArray = {This ", "is", " a", " string", " that", " will ", "be", " displayed."};
new Test().method(stringArray);
Если вы посмотрите на тест Класс ниже вы можете увидеть, что требуется только один метод:
public class Test {
public void method(String... args) {
if (args.length > 0) {
// Build the string from the supplied string arguments...
StringBuilder sb = new StringBuilder();
for (String strg : args) {
// A 'Ternary Operator' is used below in case an argument is null.
sb.append(strg == null ? "" : strg);
}
System.out.println(sb.toString()); // Display built string in console.
}
}
Что вы можете сделать, если параметр для этого метода был: Object... args
?
Иногда я использую эту технику и для конструкторов классов, например:
public class Test {
// Class Constructor
public Test (String... args) {
method(args);
}
public void method(String... args) {
if (args.length > 0) {
// Build the string from the supplied string arguments...
StringBuilder sb = new StringBuilder();
for (String strg : args) {
// A 'Ternary Operator' is used below in case an argument is null.
sb.append(strg == null ? "" : strg);
}
System.out.println(sb.toString()); // Display built string in console.
}
}
И для ее использования:
String[] stringArray = {"This ", "is", " a ", "string", " that", " will ", "be", " displayed."};
new Test(stringArray); // You will notice a warning but it works.
or
new Test(); // You will notice a warning but it works.
or
new Test("This is one Argument"); // You will notice a warning but it works.
or
new Test("This ", "is", " many ", "Arguments."); // You will notice a warning but it works.
or
Test test = new Test("This ", "is", " many ", "Arguments.");
or
Test test = new Test();
test.method("This is one Argument");
or
String[] args = {"This ", "is", " many ", "Arguments."};
Test test = new Test(args);
test.method(args);
В последнем примере будет отображаться: This is many Arguments.
дважды в консоли. Вы понимаете почему?