fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. import java.lang.reflect.ParameterizedType;
  5.  
  6. abstract class Mumble<T> {
  7. public abstract Mumble<Integer> getInstance();
  8.  
  9. protected T something;
  10.  
  11. @SuppressWarnings("unchecked")
  12. public Mumble<Integer> reflectInstance() throws Exception {
  13. Class<? extends Mumble> clazz = getClass();
  14. // Dirty implicit unchecked cast
  15. Mumble<Integer> obj = clazz.newInstance();
  16. obj.something = 20;
  17.  
  18. return obj;
  19. }
  20.  
  21. @SuppressWarnings("unchecked")
  22. public void selfTest() throws Exception {
  23. // Dirty
  24. Mumble<Integer> obj = (Mumble<Integer>) this;
  25. System.out.println("this class = " + obj.getClass().getName());
  26. // Mumble.something can hold any Object, this is why it is dirty
  27. // something should be an Integer right? Wrong.
  28. System.out.println("\tobj.something = " + obj.something);
  29. obj = getInstance();
  30. System.out.println("getInstance() class = " + obj.getClass().getName());
  31. System.out.println("\tobj.something = " + obj.something);
  32. obj = reflectInstance();
  33. System.out.println("reflectInstance() class = " + obj.getClass().getName());
  34. System.out.println("\tobj.something = " + obj.something);
  35.  
  36. }
  37. }
  38. class Bumble<T> extends Mumble<T> {
  39. @Override
  40. public Mumble<Integer> getInstance() {
  41. Bumble b = new Bumble<Integer>();
  42. b.something = 10;
  43. return b;
  44. }
  45. }
  46.  
  47.  
  48. class Ideone{
  49. public static void main (String[] args) throws java.lang.Exception {
  50. Bumble<String> bumble = new Bumble<String>();
  51. bumble.something = "I'm a String";
  52. bumble.selfTest();
  53. }
  54. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
this class = Bumble
	obj.something = I'm a String
getInstance() class = Bumble
	obj.something = 10
reflectInstance() class = Bumble
	obj.something = 20