Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. class Base
  2. {
  3. static void foo()
  4. {
  5. // I want to get Derived class here
  6. // Derived.class
  7. }
  8. }
  9.  
  10. class Derived extends Base
  11. {
  12. }
  13.  
  14. Derived.foo();
  15.  
  16. class Base
  17. {
  18. static void foo(Class< T > calledBy)
  19. {
  20. // I want to get Derived class here
  21. // Derived.class
  22. }
  23. }
  24.  
  25. class Derived extends Base
  26. {
  27. }
  28.  
  29. Derived.foo(Derived.class);
  30.  
  31. class Base {
  32. static void foo() {
  33. // Only the static context is available here so you can't get class dynamic class information
  34. }
  35. void bar() {
  36. System.out.println(getClass());
  37. }
  38. }
  39. class Derived extends Base {
  40. }
  41. class Another extends Base {
  42. static void foo() {
  43. // No super call possible!
  44. // This method hides the static method in the super class, it does not override it.
  45. }
  46. void bar() {
  47. super.bar();
  48. }
  49. }
  50.  
  51. Derived derived = new Derived();
  52. derived.bar(); // "class Derived"
  53. Base base = new Base();
  54. base.bar(); // "class Base"
  55.  
  56. // These are only "shortcuts" for Base.foo() that all work...
  57. derived.foo(); // non-static context
  58. Derived.foo(); // could be hidden by a method with same signature in Derived
  59. base.foo(); // non-static context
  60.  
  61. Base.foo(); // Correct way to call the method
  62.  
  63. Another a = new Another();
  64. a.foo(); // non-static context
  65. Another.foo();
  66.  
  67. protected static Class<?> getModelClass(int dept) throws ClassNotFoundException {
  68. Class<?> clazz = null;
  69. try {
  70. throw new Exception("dummy");
  71. } catch (Exception ex) {
  72. StackTraceElement[] trace = ex.getStackTrace();
  73. StackTraceElement e = trace[dept];
  74. String name = e.getClassName();
  75. clazz = Class.forName(name);
  76. }
  77. return clazz;
  78. }
  79.  
  80. Derived.foo();
  81.  
  82. class Base {
  83. static void foo() {
  84. System.out.println("Base");
  85. }
  86. }
  87.  
  88. class Der extends Base {
  89. static void foo() {
  90. System.out.println("Der");
  91. }
  92. }
  93.  
  94. class Check {
  95. public static void main(String[] args) {
  96. Base.foo();
  97. Der.foo();
  98. }
  99. }
  100.  
  101. javac -g Check.java && java Check
  102. Base
  103. Der
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement