Difference between revisions of "Metaclasses"

From Suhrid.net Wiki
Jump to navigationJump to search
Line 17: Line 17:
  
 
* e.g. getMethods return objects which are of type Method class. Instances of java.lang.reflect.Method are methods.  
 
* e.g. getMethods return objects which are of type Method class. Instances of java.lang.reflect.Method are methods.  
* The method class defines behavior of all methods, for e.g. getReturnType(), getModifiers() etc.  
+
* The method class defines behavior of all methods, so it is a meta-method. for e.g. getReturnType(), getModifiers() etc.  
  
 
* java.lang.Class is not a complete class, since it is declared as final. We cannot add behavior to it or specialize it.
 
* java.lang.Class is not a complete class, since it is declared as final. We cannot add behavior to it or specialize it.
  
 +
* This whole meta thing is '''reflection''' - a program can reflect on itself.
 +
* Useful for tools. e.g. Eclipse. Automatic method drop down possibly reflects on the Class object and gets all its declared methods.
  
 
[[Category:OODE]]
 
[[Category:OODE]]

Revision as of 06:54, 17 December 2011

  • Each object belongs to a class.
  • But, Everything is an object.
  • So, classes are objects apart from being classes.
String s = "Hello";
Class stringClassObj = s.getClass();
  • So the class object (stringClassObj) is an instance of which class ?
  • It is an instance of java.lang.Class.
  • java.lang.Class extends java.lang.Object since classes are objects.
  • So java.lang.Class is a metaclass. Instances of java.lang.Class are classes.
  • A class defines the behaviour of its instances. Similarly, a metaclass defines the behavior of the classes that are its instances.
  • E.g. java.lang.Class has methods that defined the behavior of its instances.
    • e.g. getName(), getDeclaredFields(), getMethods(),
  • e.g. getMethods return objects which are of type Method class. Instances of java.lang.reflect.Method are methods.
  • The method class defines behavior of all methods, so it is a meta-method. for e.g. getReturnType(), getModifiers() etc.
  • java.lang.Class is not a complete class, since it is declared as final. We cannot add behavior to it or specialize it.
  • This whole meta thing is reflection - a program can reflect on itself.
  • Useful for tools. e.g. Eclipse. Automatic method drop down possibly reflects on the Class object and gets all its declared methods.