fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.function.*;
  5. import java.lang.*;
  6. import java.io.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. // used in both chains
  14. K k1 = new K1();
  15. K k2 = new K2();
  16. // construct A chain
  17. K3A specificA = new K3A();
  18. Function<A, A> handleA = a -> specificA.handle(a);
  19. handleA = handleA.compose(k2::handle);
  20. handleA = handleA.compose(k1::handle);
  21. // try with A
  22. A sampleA = new A();
  23. handleA.apply(sampleA);
  24. // construct B chain
  25. K3B specificB = new K3B();
  26. Function<B,B> handleB = b -> specificB.handle(b);
  27. handleB = handleB.compose(k2::handle);
  28. handleB = handleB.compose(k1::handle);
  29. // try with B
  30. B sampleB = new B();
  31. B result = handleB.apply(sampleB); // you can even get a B result from the whole chain
  32. }
  33. }
  34.  
  35. interface S {}
  36. class A implements S {}
  37. class B implements S {}
  38.  
  39. interface K {
  40. <T>T handle(T t);
  41. }
  42. class K1 implements K {
  43. public <T>T handle(T t) { System.out.println("K1 handling T"); return t; }
  44. }
  45.  
  46. class K2 implements K {
  47. public <T>T handle(T t) { System.out.println("K2 handling T"); return t; }
  48. }
  49. class K3A implements K {
  50. public <T>T handle(T t) { throw new IllegalArgumentException("Can only handle A"); }
  51. public A handle(A a) { System.out.println("K3 handling A"); return a; }
  52. }
  53. class K3B implements K {
  54. public <T>T handle(T t) { throw new IllegalArgumentException("Can only handle B"); }
  55. public B handle(B b) { System.out.println("K3 handling B"); return b; }
  56. }
  57.  
Success #stdin #stdout 0.07s 33576KB
stdin
Standard input is empty
stdout
K1 handling T
K2 handling T
K3 handling A
K1 handling T
K2 handling T
K3 handling B