fork download
  1. import java.lang.reflect.Constructor;
  2. import java.util.Arrays;
  3.  
  4. class Example
  5. {
  6. public Example(String a) {
  7. System.out.println("one param: " + a);
  8. // ...
  9. }
  10.  
  11. public Example(String a, String b) {
  12. System.out.println("two params: " + a + ", " + b);
  13. // ...
  14. }
  15.  
  16. public Example(String a, String b, String c) {
  17. System.out.println("three params: " + a + ", " + b + ", " + c);
  18. // ...
  19. }
  20.  
  21. static Example create(String... strings) {
  22. try {
  23. Class[] paramTypes = new Class[strings.length];
  24. Arrays.fill(paramTypes, String.class);
  25. Constructor ctor = Example.class.getConstructor(paramTypes);
  26. return (Example)ctor.newInstance((Object[])strings);
  27. } catch (Exception e) {
  28. throw new IllegalArgumentException(strings.length + " strings not supported");
  29. }
  30. }
  31.  
  32. public static void main (String[] args)
  33. {
  34. Example e = Example.create("a", "b", "c");
  35. }
  36. }
  37.  
Success #stdin #stdout 0.08s 27784KB
stdin
Standard input is empty
stdout
three params: a, b, c