From Suhrid.net WikiJump to navigationJump to search
- 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.
- Metaclasses are also a kind of design. e.g. we can have classes Aircraft and AircraftType. AircrafType is the metaclass of Aircraft. e.g specifies what the behaviour of an Aircraft must be. instances an AircraftType can be jetLiner:AircraftType fighter:AircraftType etc. which specify behaviour for that aircraft type (these are actually classes). a 747-400 will be an instances of jetLiner:AircraftType.
- 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.