fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. interface Interface {
  8. }
  9.  
  10. class Foo implements Interface {
  11. Foo(int magicInt) { magicInt = magicInt + 1; /* do some fancy calculations */ }
  12. }
  13.  
  14. class Bar implements Interface {
  15. Bar(int magicInt) { magicInt = magicInt + 2; /* do some fancy calculations */ }
  16. }
  17.  
  18. class Factory<T extends Interface> {
  19. int magicInt = 0;
  20.  
  21. T createNewObject(Class<T> typeToMake) {
  22. final java.lang.reflect.Constructor<T> magicIntConstructor;
  23. try {
  24. magicIntConstructor = typeToMake.getDeclaredConstructor(Integer.TYPE);
  25. } catch (NoSuchMethodException e) {
  26. throw new RuntimeException("No valid constructor!");
  27. }
  28. final T t;
  29. try {
  30. t = magicIntConstructor.newInstance(magicInt);
  31. throw new RuntimeException("Couldn't instantiate.");
  32. }
  33. return t;
  34. }
  35. }
  36.  
  37. /* Name of the class has to be "Main" only if the class is public. */
  38. class Ideone
  39. {
  40. public static void main (String[] args) throws java.lang.Exception
  41. {
  42. Factory<Foo> fooFactory = new Factory<Foo>();
  43. Foo foo = fooFactory.createNewObject(Foo.class);
  44. System.out.println(foo);
  45.  
  46. Factory<Bar> barFactory = new Factory<Bar>();
  47. Bar bar = barFactory.createNewObject(Bar.class);
  48. System.out.println(bar);
  49. }
  50. }
  51.  
Success #stdin #stdout 0.1s 320576KB
stdin
Standard input is empty
stdout
Foo@10dea4e
Bar@1909752