Difference between revisions of "Metaclasses"

From Suhrid.net Wiki
Jump to navigationJump to search
Line 12: Line 12:
 
* java.lang.Class extends java.lang.Object since classes are objects.
 
* 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.
 
* 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.
+
* 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. java.lang.Class has methods that defined the behavior of its instances.  
 
** e.g. getName(), getDeclaredFields(), getMethods(),  
 
** e.g. getName(), getDeclaredFields(), getMethods(),  

Revision as of 04:38, 7 January 2012

  • 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.