fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.lang.reflect.*;
  6. import java.io.*;
  7.  
  8. class Ideone {
  9. public static void main (String[] args) throws java.lang.Exception {
  10. Builder[] registry = { new CircleBuilder()
  11. , new SquareBuilder()
  12. , new RectangleBuilder()
  13. };
  14.  
  15. for (Builder<?> b : registry) b.shape().draw();
  16. }
  17. }
  18.  
  19. interface Shape {
  20. void draw();
  21. }
  22.  
  23. class Rectangle implements Shape {
  24. public void draw() { System.out.println("Rect"); }
  25. }
  26.  
  27. class Square extends Rectangle {
  28. public void draw() { System.out.println("Square"); }
  29. }
  30.  
  31. class Circle implements Shape {
  32. public void draw() { System.out.println("Circle"); }
  33. }
  34.  
  35. class Builder<SHAPE extends Shape> {
  36.  
  37. public final SHAPE shape = build();
  38.  
  39. @SuppressWarnings("unchecked")
  40. private SHAPE build() {
  41. try {
  42. ParameterizedType parent =
  43. (ParameterizedType) getClass().getGenericSuperclass();
  44. Class<?> arg = (Class<?>) parent.getActualTypeArguments()[0];
  45. return (SHAPE) arg.newInstance();
  46. } catch (ReflectiveOperationException e) {
  47. throw new RuntimeException(e);
  48. }
  49. }
  50.  
  51. public SHAPE shape() { return shape; }
  52. }
  53.  
  54. class CircleBuilder extends Builder<Circle> {}
  55.  
  56. class RectangleBuilder extends Builder<Rectangle> {}
  57.  
  58. class SquareBuilder extends Builder<Square> {}
Success #stdin #stdout 0.08s 381248KB
stdin
Standard input is empty
stdout
Circle
Square
Rect