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("(String): " + a);
  8. // ...
  9. }
  10.  
  11. public Example(int a, String b) {
  12. System.out.println("(int, String): " + a + ", " + b);
  13. // ...
  14. }
  15.  
  16. public Example(String a, String b) {
  17. System.out.println("(String, String): " + a + ", " + b);
  18. // ...
  19. }
  20.  
  21. static Example create(Object... params) {
  22. try {
  23. Class[] paramTypes = new Class[params.length];
  24. for (int n = 0; n < params.length; ++n) {
  25. Class cls = params[n].getClass();
  26. if (cls.equals(Integer.class)) { // You may need this (for int and other primitives)
  27. paramTypes[n] = Integer.TYPE;
  28. } else {
  29. paramTypes[n] = cls;
  30. }
  31. }
  32. Constructor ctor = Example.class.getConstructor(paramTypes);
  33. return (Example)ctor.newInstance(params);
  34. } catch (Exception e) {
  35. System.out.println(e.getMessage());
  36. e.printStackTrace(System.out);
  37. throw new IllegalArgumentException("parameters not supported");
  38. }
  39. }
  40.  
  41. public static void main(String[] args)
  42. {
  43. Example e1 = Example.create("foo");
  44. Example e2 = Example.create(1, "foo");
  45. Example e3 = Example.create("foo", "bar");
  46. }
  47. }
  48.  
Success #stdin #stdout 0.1s 27660KB
stdin
Standard input is empty
stdout
(String): foo
(int, String): 1, foo
(String, String): foo, bar